如何将这个宏转换为函数模板?
How do I convert this macro to a function template?
在使用bind实现调度表的过程中,我试图用函数模板替换宏。
一旦我开始添加返回std::string
或double
的表,我将强烈倾向于模板版本。
宏版本工作正常,但模板版本转储核心。
有人能解释一下我做错了什么吗?谢谢你。
#include <functional>
#include <iostream>
#include <map>
struct Integer
{
virtual int getInt() const = 0;
};
struct IntImpl : public Integer
{
virtual int getInt() const { return 42; }
};
typedef std::function<int()> IntFunction;
typedef std::function<IntFunction( Integer const& inst )> IntLambda;
#define USE_MACRO
#ifdef USE_MACRO
#define MP(A,B)
std::make_pair( A, []( Integer const& inst ) {
return std::bind( B, std::cref( inst ));
} )
#else
template<typename L,typename T,typename M>
std::pair<std::string,L>
MP( std::string const& str, M method)
{
return std::make_pair( str, [&method]( T const& inst ) {
return std::bind( method, std::cref( inst ));
}
);
}
#endif
static std::map<std::string,IntLambda> const g_intTbl =
{
#ifdef USE_MACRO
MP( "getInt", &Integer::getInt )
#else
MP<IntLambda,Integer>( "getInt", &Integer::getInt )
#endif
};
int
main( int argv, char* argc[] )
{
IntImpl x;
std::cerr << g_intTbl.find("getInt")->second( x )() << std::endl;
}
你的问题是如何捕获method
到你的lambda。您正在通过引用捕获method
,它引用了本地方法参数,即堆栈上的一个值。return std::bind()
直到函数被调用时才执行,此时它将尝试绑定对堆栈变量的引用,而堆栈变量显然已经不存在了。
您只需将[&method]
更改为[method]
即可按值捕获
相关文章:
- 将显式实例化的函数模板与转换匹配
- 将函数的参数 - 签名从使用 'std::function<T>' 转换为模板参数类型
- static_cast:转换函数模板——它们真的有效吗
- 使用用户定义的转换运算符推导函数模板参数
- 为什么用户定义的转换函数模板不能有推导的返回类型?
- 如何防止函数模板中的隐式转换?
- 如何类型转换为模板成员函数参数?
- 函数模板中的无效转换错误,返回值取决于其泛型类型
- 尝试将 C++11 代码转换为 C++03 时默认函数模板参数出错
- 使用模板和部分专用化生成类型转换函数
- 非调用转换函数上的模板中的编译错误
- 是否可以在函数模板中转换参数C++?
- 如何将中的函数包装器转换为模板
- 如何从函数模板类成员内的转换算法参数指向一元运算符函数
- 将函数模板转换为函数重载集
- 将函数模板化转换为函数指针
- 函数模板,用于将字符串文本转换为 std::array
- 存在函数模板时的参数转换
- 重载转换函数模板
- c++中转换函数模板实参演绎的含义