简体   繁体   中英

How to test if an std::function<T> is constructible for template argument T

I am currently writing a template class that takes a Signature template parameter and stores a std::function internally.

template <class Signature>
class Impl
{
    std::function<Signature> f;
};

This seems to work quite OK, except when the Signature template parameter is not valid, where the compiler fails with some template instantiation error in std::function.

Now because Impl clients do not need to know the internals of Impl , it would be better to output some human readable message to the fellow developer that will use Impl stating that the Signature parameter is invalid.

Using a is_invocable trait class, something like :

static_assert(is_invocable<Signature>::value, "Template parameter Signature is invalid");

When attempting to write such a trait class, I've come up with this :

template <class Signature>
struct is_invocable : std::false_type
{};

template <class Signature>
struct is_invocable <std::function<Signature>> : std::true_type
{};

This does not seem to work however, because is_invocable does not want to check if Signature is std::function but rather if it is possible to construct a std::function<T> with T being the template parameter Signature .

How would it be possible to write a is_invocable class ?

Note: c++17 is not available.

As StoryTeller suggested in the comments, you want std::is_function here, as the template parameter that you pass to std::function must be a signature .

template <class Signature>
struct Impl
{
    static_assert(std::is_function<Signature>::value, "");
    std::function<Signature> f;
};

std::function will check whether its function object is invocable with Signature for you.

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