Templates std::bind with template成员函数
我有一个奇怪的问题,我不能绑定这个模板成员函数, 所有这些代码编译: 这是一个简单的代码:我有一个Templates std::bind with template成员函数,templates,c++11,std-function,stdbind,function-binding,Templates,C++11,Std Function,Stdbind,Function Binding,我有一个奇怪的问题,我不能绑定这个模板成员函数, 所有这些代码编译: 这是一个简单的代码:我有一个ExecutionList,它应该在std::vector中保存可调用的函数。我现在可以通过调用ExecutionList::addFunctor来添加函数。但是在那里,我不能绑定到模板void Functor::calculate(T*T)。我在问我为什么,这里缺少了什么,编译器无法以某种方式推断出我写的东西 m_calculationList.push_back( std::bind(&
ExecutionList
,它应该在std::vector
中保存可调用的函数。我现在可以通过调用ExecutionList::addFunctor
来添加函数。但是在那里,我不能绑定到模板void Functor::calculate(T*T)
。我在问我为什么,这里缺少了什么,编译器无法以某种方式推断出我写的东西
m_calculationList.push_back( std::bind(&T::calculate<Type>, extForce, std::placeholders::_1 ) );
m_calculationList.push_-back(std::bind(&T::calculation,extForce,std::placeholders::_1));
*错误:*
错误:在'>'标记之前应该有主表达式
m_calculationList.push_back(std::bind(T::calculation,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);
}
#包括
#包括
#包括
结构MyType{
静态int a;
国际货币基金组织;
MyType(){a++;m_a=a;}
作废打印(){
std::cout看起来您缺少template关键字。如果T是一个模板参数,而T::calculate引用了一个模板,则需要告诉编译器calculate是一个模板,而不是某个静态变量,您尝试使用小于运算符与其他变量进行比较:
T::template calculate<Type>
T::模板计算
几年前我遇到了完全相同的问题,但今天(C++11之后),我可能会使用更简单的lambda来解决它:
std::function<void(Type*)> func = [obj](Type*param){obj.calculate(param);};
std::function func=[obj](Type*param){obj.calculate(param);};
无论如何,试着减少新使用的数量。寻找更好的方法来管理你的资源。你的代码似乎泄漏了几个函数。这意味着我需要一些typename
word?这有意义吗,因为它不是一个类型而是一个函数指针这里有另一个消除歧义的方法:template
std::bind(&T::template calculate,…)
应该有效。另外,始终包含您收到的错误消息。“不起作用”没有帮助。啊,该死的,我认为这是一件愚蠢的事情,但从未在类型前面使用过模板,只是有时在a.template foo
的情况下,如果foo
是不可推断的
std::function<void(Type*)> func = [obj](Type*param){obj.calculate(param);};