mardi 27 février 2018

How to test if an std::function

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

template <class Signature>
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.

Aucun commentaire:

Enregistrer un commentaire