【问题标题】:Overload Templated Function for All String Types所有字符串类型的重载模板函数
【发布时间】:2013-07-18 07:19:16
【问题描述】:
我有以下模板:
template<class T>
void fn(T t){ }
并且我想覆盖它的行为,任何可以转换为std::string的东西。
使用std::string 参数指定显式模板特化和非模板函数重载仅适用于传入std::string 的调用,而不适用于其他函数,因为它似乎将它们与模板匹配在尝试参数转换之前。
有没有办法实现我想要的行为?
【问题讨论】:
标签:
c++
template-specialization
overloading
【解决方案1】:
类似这种情况的东西在 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,你也可以手动实现,或者使用 boost。