是否可以从(函子成员的)函数签名中检索参数类型以在模板中使用?
假设您有一个函子:
struct MyFunctor
{
bool operator ()( int value )
{
return true;
}
};
是否可以检索函子的成员的参数类型以在模板中使用?以下是这个神话功能的用法:
template < typename FunctorType >
bool doIt( FunctorType functor, typename FunctorType::operator()::arg1 arg )
{
return functor( arg );
}
是否有有效的语法可以替代我的神话 FunctorType::operator()::arg1
?
Assume you have a functor:
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 );
}
Is there a valid syntax that would substitute for my mythical FunctorType::operator()::arg1
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您知道该项目是一个函子,那么您可以直接获取它的operator(),如下所示:
对我来说,该程序打印出:
关键点是Arg0
Arg1
分别是long
和int*
。If you know the item is a functor, then you can just grab its
operator()
, like so:For me, that program prints out:
The key point being that
Arg0
andArg1
arelong
andint*
, respectively.不,没有。最优雅的方法是要求函子为参数类型提供 typedef,或者引入特征类。如果您希望模板使用函子和函数,则后者很有用。
或者,您可以将参数类型设置为第二个模板参数:
如果
ArgumentType
与函子所需的类型不匹配,编译器仍然会抱怨。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:
The compiler will still complain if
ArgumentType
does not match the type required by the functor.你可以用 C++0x 来做
You can sort of do it in C++0x
在这里,我对 @BjörnPollex(正确)答案进行了 C++11 更新。
回到问题,你想明确指定 doIt 的第二个参数,主要是为了限制可以传递的内容。在 C++11 中,您可以在不明确知道函子的参数类型的情况下暗示此限制(如果函子无论如何重载,则不会很好地定义)。
(转换为
bool
可能根本没有必要,我把它放在这里是因为您似乎确实希望返回类型为bool
)。此 doIt(模板)函数将采用可能与函子参数兼容的任何参数(也可转换为 bool)。如果传递的参数不兼容,该函数甚至根本不存在,并且会产生一个优雅的“doIt function not found”编译器错误。
我们可以更进一步,使用完美前向使
doIt
与functor(arg)
完全等价:Here I give a C++11 update to @BjörnPollex (correct) answer.
Going back the question, you want to specify the second argument of
doIt
explicitly mainly to restrict what can be passed. In C++11 you can imply this restriction without knowing explicitly the argument type of the functor (which is not well defined if the functor overloaded anyway).(the conversion to
bool
may not be even necessary, I put it here because it seem that you really want the return type to bebool
).This
doIt
(template) function will take any argument that is possibly compatible with afunctor
argument (and also convertible tobool
). If the argument passed is not compatible the function will not even exist at all, and will produce an elegant "doIt function not found" compiler error.One can go one step more by using perfect forward to make
doIt
exactly equivalent tofunctor(arg)
: