0
template<typename T>
class Pack
{
private:
    std::function<T()> _Func = nullptr;
public:
    Pack()
    {
    }
    Pack(std::function<T()> func)
        : _Func(func)
    {
    }
    ~Pack()
    {
    }

    operator T()
    {
        return _Func();
    }
};

What I use is operator T, I want to call _Func implicitly but I cannot even do it explicitly. It seems right but actually error C2440 @MSVC. I use it in two ways:

  1. static member of class (succeeded);

  2. member of class (failed)

(I don't know whether it matters or not)

I'm really wondering why it performs in two ways, and more importantly, how I can put it into my class as a non-static member and successfully call the operator T.

PENGUINLIONG
  • 533
  • 1
  • 4
  • 11
  • You need to bind a non-static function to an object: Maybe [this](http://stackoverflow.com/questions/7582546/using-generic-stdfunction-objects-with-member-functions-in-one-class) helps. – namezero May 16 '15 at 09:36
  • @namezero param is a lambda expression captures all by references in class. The same solution? – PENGUINLIONG May 16 '15 at 09:41
  • @namezero What's the question? your example works fine. – Ami Tavory May 16 '15 at 09:50
  • @AmiTavory If i put it into a class as an dynamic member, the `operator T` won't be automatically called if I write like this: int i = ClassInstance.IntPack; – PENGUINLIONG May 16 '15 at 09:57
  • It actually does just that in g++. If it doesn't do it in Visual, I suggest you add this to the tag of your question. – Ami Tavory May 16 '15 at 10:01
  • @AmiTavory That's strange. – PENGUINLIONG May 16 '15 at 10:30
  • Why's that strange. Compilers, especially VC++, don't always do things right. I strongly suggest you add this to your question tag, as it's currently misleading. – Ami Tavory May 16 '15 at 10:56

1 Answers1

2

Member of the class:

struct test
{
    test()
    {
        p_ = Pack<int>(std::bind(&test::foo, *this));
    }

    int foo()
    {
        std::cout << "test::foo" << std::endl;
        return 5;
    }

    Pack<int> p_;
};

int main()
{
    test t;
    int x = t.p_;

    return 0;
}

This works fine on VS 2013 EE.

doqtor
  • 8,414
  • 2
  • 20
  • 36
  • I mean, the Pack is in a class and i want to use it in main() through the instance of the class – PENGUINLIONG May 16 '15 at 11:00
  • @PENGUINLIONG what is your compiler version? This code works even on VS2010 if I remove _Func initialization within the class. – doqtor May 16 '15 at 11:47
  • My suggestion will be to try Pack class with my code in a new empty project and if that is not working then install updates - I compiled the code using VS2013 update 4. – doqtor May 16 '15 at 11:53