我有一个奇怪的问题,我无法绑定这个模板成员函数,所有这些代码都编译: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);
}