简体   繁体   中英

Using std::bind in Variadic Template Classes

I'm attempting to build a simple class to wrap around functions and call (possibly return) them without passing any values except during constructing the class. The problem with this, however, is that I can't seem to reach the level of ambiguity necessary. The sample code I have is as follows:

template< typename T, typename... Arguments>
struct FunctionPtrWrapper
{
    FunctionPtrWrapper(T(*funcIn)(Arguments...), Arguments... args)
    {
        funcPtr=std::bind(funcIn, args...);
    }
    void go()
    {
        funcPtr();
    }
    std::function< T(Arguments...)> funcPtr;
};

It compiles fine and even runs when passed functions without arguments, but when passing a function that requires arguments, it will fail to compile if go() is called, so that:

FuctionPtrWrapper<void> pointerOne(&foo);
pointerOne.go();

works perfectly, but:

FunctionPtrWrapper<void, char> pointerTwo(&foo, 'c');
pointerTwo.go();

Fails to compile with the following error:

error: no match for call to '(std::function< void(char)>) ()

Which I assume means that somehow in the constructor, the argument fails to expand and pass to the call to std::bind. Is this a syntactical error, misuse of the used functions or simply not possible?

Your std::bind call bound all the parameters, so the function object returned by it should be invoked without a parameter.

Thus, the std::function 's type parameter should always be T() , not T(Arguments...) :

std::function<T()> funcPtr;

Demo .

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