如何将这个宏转换为函数模板?

How do I convert this macro to a function template?

本文关键字:转换 函数模板      更新时间:2023-10-16

在使用bind实现调度表的过程中,我试图用函数模板替换宏。

一旦我开始添加返回std::stringdouble的表,我将强烈倾向于模板版本。

宏版本工作正常,但模板版本转储核心。

有人能解释一下我做错了什么吗?谢谢你。

#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]即可按值捕获