我正在尝试了解使用 std::enable_if<>
的模板函数的不同版本。
版本 1:
template<class T,typename std::enable_if<std::is_convertible<T,std::string_view>::value,T>::type* = nullptr>
void foo(const T& msg);
版本 2:
template<class T,typename = typename std::enable_if<std::is_convertible<T,std::string_view>::value>::type>
void foo(const T& msg);
如果我理解正确,如果满足条件,它们应该转换为:
// Version 1
template<class T,T* = nullptr>
void foo(const T& msg);
// Version 2
template<class T,typename = void>
void foo(const T& msg);
两个版本都可以通过以下方式同等调用:
std::string s = "Test";
foo(s);
这两个版本有什么区别?什么时候用?
第二个问题
由于我的一个错误,我发现如果缺少一个类型名,版本 2 也可以编译:
//Correct Version 2 like above:
template<class T,std::string_view>::value>::type>
void foo(const T& msg);
// My error version. Also works. Is this also correct?
template<class T,typename = std::enable_if<std::is_convertible<T,std::string_view>::value>::type>
void foo(const T& msg);
第二个版本也正确吗?我认为 std::enable_if<>
前面确实需要一个 typename
。