我有以下模板:
template<class T>
void fn(T t){ }对于任何可以转换为std::string的东西,我都想覆盖它的行为。
使用参数作为std::string指定显式模板专门化和非模板函数重载都只适用于传入std::string的调用,而不适用于其他函数,因为它似乎在尝试参数转换之前将它们与模板匹配。
有没有办法实现我想要的行为?
发布于 2013-07-18 15:25:08
在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。
https://stackoverflow.com/questions/17717042
复制相似问题