将重载函数作为模板传递

时间:2011-04-16 05:58:19

标签: c++ templates overloading

我有这个模板集

        __Self &set(const char *name, lua_CFunction func)
        { return rawSet(name, FuncCall::create(func)); }
....

我用的是:

.set("child_value", &pugi::xml_node::child_value)

但是child_value超载了

const char_t* xml_node::child_value(const char_t* name) const
const char_t* xml_node::child_value() const

并且编译器发出此错误:

error C2668: 'SLB::Class<T,W>::set' : ambiguous call to overloaded function

我怎么能解决这个错误?我想要child_value()版本。

3 个答案:

答案 0 :(得分:2)

我认为需要明确的演员:
.set( "child_value", static_cast<const char_t* (xml_node::*)() const>( &pugi::xml_node::child_value ) );

答案 1 :(得分:2)

将typedef定义为:

typedef const char_t* (pugi::xml_node::*fn_pchar)(const char_t* name) const;
typedef const char_t* (pugi::xml_node::*fn_void)() const;

然后写:

//if you want to select first member function that takes parameter (char*)
set("child_value", (fn_pchar)&pugi::xml_node::child_value); 
                  //^^^^^^^^ note this!

//if you want to select second member function that takes no parameter (void)
set("child_value", (fn_void)&pugi::xml_node::child_value); 
                  //^^^^^^^ note this

答案 2 :(得分:0)

行, 我自己做了。

typedef const char* (pugi::xml_node::*ChildValueFunctionType)(void) const; // const required!
ChildValueFunctionType ChildValuePointer = &pugi::xml_node::child_value;

然后,只需致电

.set("child_value", ChildValuePointer)