是否可以从(Functor成员的)函数签名中检索参数类型以在模板中使用? [英] Is it possible to retrieve the argument types from a (Functor member's) function signature for use in a template?
问题描述
假设你有一个函子:
struct MyFunctor
{
bool operator ()( int value )
{
return true;
}
};
是否可以检索函子的成员参数类型以在模板中使用?下面是这个神话功能的用途:
Is it possible to retrieve a functor's member's argument type for use within your template? The following is a use of this mythical functionality:
template < typename FunctorType >
bool doIt( FunctorType functor, typename FunctorType::operator()::arg1 arg )
{
return functor( arg );
}
是否有一个有效的语法来代替我的神话 FunctorType :: operator():: arg1
?
Is there a valid syntax that would substitute for my mythical FunctorType::operator()::arg1
?
推荐答案
最简单的方法是要求你的函数为参数类型提供一个 typedef
,或引入一个traits类。
No there is not. The most elegant way to do this would be to either require your functors to provide a typedef
for the argument-type, or to introduce a traits-class. The latter is useful if you want your template to work with functors and functions.
或者,您可以让参数类型为第二个模板参数:
Alternatively, you can just make the argument type a second template parameter:
template < typename FunctorType, class ArgumentType >
bool doIt( FunctorType functor, ArgumentType arg )
{
return functor( arg );
}
编译器仍然会提出 ArgumentType
与函子所需的类型不匹配。
The compiler will still complain if ArgumentType
does not match the type required by the functor.
这篇关于是否可以从(Functor成员的)函数签名中检索参数类型以在模板中使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!