2013-07-18 22 views
5

我有以下模板:过载模板函数的所有字符串类型

template<class T> 
void fn(T t){ } 

,我想重写其行为对任何可以被转换为std::string

两个规定明确的模板专业化与参数作为std::string一个非模板函数重载只为传递一个std::string而不是其他函数的调用工作,因为它似乎在试图论证之前他们匹配模板转换。

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

回答

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); 
} 

live example

和当然,您也可以手动实现它,如果你没有C++ 11,或者使用升压。