2012-09-18 54 views
1
template< typename T > 
void addVarCB(const std::string &name, 
       TwSetVarCallback setCallback, TwGetVarCallback getCallback, 
       void * clientData, const std::string &def = ""); 

template< class C, typename T > 
void addVarCB(const std::string &name, 
       C * _this, T(C::*getter)(void), const std::string &def = ""); 

下面的代码可以编译和崩溃运行时:意外模板扣

bar_->addVarCB<MyClass, unsigned>("foo", this, &MyClass::MyClassFn, nullptr); 

我真的希望它没有在所有编译,因为没有函数,它的参数作为参数! (请注意, “MyClass的,无符号” 是不必要的,但仅仅是明确的......)

回答

6

可悲的是,std::stringnullptr构造,可看到here,具体(5)

basic_string(const CharT* s, // <== 'nullptr' matches here 
       const Allocator& alloc = Allocator()); 

注:

5)用s指向的以空字符结尾的字符串的内容构造字符串。字符串的长度由第一个空字符决定。 s一定不能是NULL指针。

5

第一条评论是这与模板扣除无关。由于您提供了模板参数,因此不会使用任何推演,并使用第二个模板。

函数调用编译为存在来自nullptrconst char*转换,可用于调用std::string构造函数一个const char*。该构造函数的契约要求指针是有效的,并指向代码中为空的字符结尾序列。

+0

对于第一段+1,完全忘了提及。 – Xeo