![](/img/trans.png)
[英]Template function taking any functor and returning the type of the functor return
[英]boost function to any functor with template operator ()
我想存储boost::function<void(void*)>
以便指向任意仿函数类对象。 我尝试了以下代码,但无法编译:
struct MyFunctor
{
template<class T>
void operator()(T* a)
{
T& ref = *a;
}
};
struct MyFunctor2
{
template<class T>
void operator()(T* a)
{
T& ref = *a;
}
};
boost::function<void(void*)> anyFunctorPtr;
anyFunctorPtr= MyFunctor();
double a = 5;
anyFunctorPtr(&a);
编译器错误为错误C2182:'ref':非法使用'void'类型
boost::function
,就像std::function
需要一个特定的仿函数签名(在您的情况下为void(void*)
)一样,这是它将尝试用其调用仿函数的签名。 这就是为什么T
被推定为void
,并且编译器拒绝为您提供void&
。
您的示例从根本上增加了可能性,因为如果您要进行类型擦除,就不能有模板,因为编译器无法知道要实例化哪些模板。 假设一会儿boost::function<magic>
可以做你想要的。
如果您给编译器这样的代码:
void foo(boost::function<magic> func)
{
double a = 5;
func(&a);
}
编译器将如何知道是否为MyFunctor
或MyFunctor2
生成T = double
实例化? 它根本不知道,因此无法生成正确的代码。 对于可以使用的模板函子类的数量以及可以尝试调用operator()
的类型的数量没有限制,因此自动提前实例化它们也是不可能的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.