简体   繁体   中英

C++ User-defined type conversion failure

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM