使用Boost传递类函数时出错

Invalid Template Error passing class function using Boost

本文关键字:出错 类函数 Boost 使用      更新时间:2023-10-16

尝试使用模板,其中参数为

template<class T, boost::function<long (T*)> &f>
static long myFunc(const vector<boost::shared_ptr<T>>   &inputVector)   
{ // do stuff}

这是我打的电话

long i = myFunc<MyClass, boost::bind(&MyClass::myClassFunc, _1)>(myInputVector);

,其中函数的签名是

long myClassFunc() const { return m_value; }

得到以下编译错误:

错误C2975: 'f': 'myFunc'的模板参数无效,期望的编译时常量表达式

我需要什么来编译这个?

将参数绑定到函数是一个运行时操作。当您将一个值作为模板参数传递时,该值必须在编译时已知。将boost::函数作为参数传递。

template<class T>
static long myFunc(const vector<boost::shared_ptr<T>> &inputVector, boost::function<long (T*)> &f)   
{ // do stuff 
}

这样说:

long i = myFunc<MyClass)>(myInputVector, boost::bind(&MyClass::myClassFunc, _1));