[英]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. 我目前正在编写一个模板类,它接受一个
Signature
模板参数并在内部存储一个std :: function。
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. 这似乎工作得很好,除非
Signature
模板参数无效,编译器在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. 现在因为
Impl
客户端不需要知道Impl
的内部结构,所以最好将一些人类可读的消息输出给将使用Impl
表示Signature
参数无效的开发人员。
Using a is_invocable
trait class, something like : 使用
is_invocable
特征类,类似于:
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
. 但是这似乎不起作用,因为
is_invocable
不想检查Signature
是否是std :: function,而是可以构造一个std::function<T>
其中T
是模板参数Signature
。
How would it be possible to write a is_invocable
class ? 怎么可能写一个
is_invocable
类?
Note: c++17 is not available. 注意:c ++ 17不可用。
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 . 正如StoryTeller在评论中建议的那样,你想要
std::is_function
,因为传递给std::function
的模板参数必须是签名 。
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. std::function
将检查其函数对象是否可以使用Signature
进行调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.