我有一个奇怪的问题,我无法绑定此模板成员函数, 所有这些代码都编译成:http://ideone.com/wl5hS8
这是一个简单的代码:我有一个ExecutionList
,它应该在std::vector
中保存可调用的函数。我现在可以通过调用ExecutionList::addFunctor
来添加函数。但在那里,我无法绑定template<typename T> void Functor::calculate(T * t)
。我问我为什么,这里缺少什么,编译器不能以某种方式推断出我在
m_calculationList.push_back( std::bind(&T::calculate<Type>, extForce, std::placeholders::_1 ) );
* 错误:*
error: expected primary-expression before ‘>’ token
m_calculationList.push_back( std::bind(T::calculate<Type>, extForce, std::placeholders::_1 ) );
^
守则:
#include <functional>
#include <iostream>
#include <vector>
struct MyType{
static int a;
int m_a;
MyType(){a++; m_a = a;}
void print(){
std::cout << "MyType: " << a << std::endl;
}
};
int MyType::a=0;
struct Functor{
static int a;
int m_a;
Functor(){a++; m_a = a;}
// Binding this function does not work
template<typename T>
void calculate(T * t){}
// Binding this function works!!!
void calculate2(MyType * t){
std::cout << " Functor: " << m_a <<std::endl;
t->print();
}
};
int Functor::a=0;
// Binding this function works!!!
template<typename T>
void foo( T * t){}
class ExecutionList{
public:
typedef MyType Type;
template<typename T>
void addFunctor(T * extForce){
//m_calculationList.push_back( std::bind(&T::calculate<Type>, extForce, std::placeholders::_1 ) ); /// THIS DOES NOT WORK
m_calculationList.push_back( std::bind(&T::calculate2, extForce, std::placeholders::_1 ) );
m_calculationList.push_back( std::bind(&foo<Type>, std::placeholders::_1 ) );
}
void calculate(Type * t){
for(auto it = m_calculationList.begin(); it != m_calculationList.end();it++){
(*it)(t); // Apply calculation function!
}
}
private:
std::vector< std::function<void (Type *)> > m_calculationList;
};
int main(){
MyType b;
ExecutionList list;
list.addFunctor(new Functor());
list.addFunctor(new Functor());
list.calculate(&b);
}
答案 0 :(得分:3)
您似乎错过了模板关键字。如果T是模板参数而T :: calculate是指模板,则需要告诉编译器计算是模板而不是某些静态变量,您尝试使用less-than运算符与其他东西进行比较:
T::template calculate<Type>
几年前我遇到了完全相同的问题,但今天(发布在C ++ 11之后)我可能会用一个更简单的lambda解决它:
std::function<void(Type*)> func = [obj](Type*param){obj.calculate(param);};
无论如何,尽量减少new
次使用的次数。寻找更好的方法来管理您的资源。您的代码似乎泄漏了几个仿函数。