gpt4 book ai didi

c++ - 使用模板运算符 () 将函数 boost 到任何仿函数

转载 作者:行者123 更新时间:2023-11-28 01:32:45 24 4
gpt4 key购买 nike

我要存储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);

编译器错误是error C2182: 'ref' : illegal use of type 'void'

最佳答案

boost::function , 就像 std::function需要一个特定的仿函数签名(在您的情况下为 void(void*) ),这是它将尝试调用您的仿函数的签名。这就是为什么 T推导为 void编译器拒绝给你 void& ,理所当然。

你的例子基本上是自相矛盾,因为如果你想进行类型删除,你就不能有模板,否则编译器无法知道要实例化哪些模板。暂时假设 boost::function<magic>可以为所欲为。

如果你给编译器这样的代码:

void foo(boost::function<magic> func)
{
double a = 5;
func(&a);
}

编译器如何知道是否生成 T = double MyFunctor 的实例化或 MyFunctor2 ?它根本不知道,因此无法生成正确的代码。您可以拥有的模板仿函数类的数量和您可以尝试调用的类型的数量没有限制 operator()与,所以提前自动实例化它们也是不可能的。

关于c++ - 使用模板运算符 () 将函数 boost 到任何仿函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50800704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com