所有字符串类型的重载模板化函数

Van*_*ril 5 c++ overloading template-specialization

我有以下模板:

template<class T>
void fn(T t){ }
Run Code Online (Sandbox Code Playgroud)

我想要覆盖任何可以转换为的行为std::string.

两者都指定显式模板特化和非模板函数重载,参数作为std::string传入std::string而不是其他函数的调用的唯一工作,因为它似乎在尝试参数转换之前将它们与模板匹配.

有没有办法实现我想要的行为?

For*_*veR 9

像这种情况的东西可以帮助你在C++ 11中

#include <type_traits>
#include <string>
#include <iostream>

template<class T>
typename std::enable_if<!std::is_convertible<T, std::string>::value, void>::type
fn(T t)
{
   std::cout << "base" << std::endl;
}

template<class T>
typename std::enable_if<std::is_convertible<T, std::string>::value, void>::type
fn(T t) 
{
   std::cout << "string" << std::endl;
}

int main()
{
   fn("hello");
   fn(std::string("new"));
   fn(1);
}
Run Code Online (Sandbox Code Playgroud)

实例

当然,你可以手动实现它,如果你没有C++ 11,或者使用boost.