Search code examples
c++castingstd-functionexplicit-conversion

explicit conversion to std::function


I'm trying to define explicit conversion from some class to std::function like this:

#include <functional>

class ExpInt { private:
    const int value;
public:
    ExpInt(const int v):value(v){}
    explicit operator std::function<int (void)> ()
    {
        return [=](void){ return value; };
    }
};

int main(int argc, char **argv)
{
    auto e = new ExpInt(44);
    auto f = static_cast<std::function<int (void)>>(e);
    return 0;
}

But when I compile it I get the following error:

$ g++ main.cpp -o main
main.cpp: In function ‘int main(int, char**)’:
main.cpp:16:51: error: no matching function for call to ‘std::function<int()>::function(ExpInt*&)’
  auto f = static_cast<std::function<int (void)>>(e);
                                                   ^

Solution

  • The compiler tells you what's wrong:

    error: no matching function for call to ‘std::function<int()>::function(ExpInt*&)’
    auto f = static_cast<std::function<int (void)>>(e);
                                                   ^
    

    A pointer to ExpInt is not convertible to std::function<int (void)>. ExpInt would be convertible, so if you simply indirect through the pointer, that would work:

    auto f = static_cast<std::function<int (void)>>(*e);
    

    P.S. You leak the dynamic allocation. Avoid using owning bare pointers.