【发布时间】:2021-12-15 08:15:47
【问题描述】:
我正在尝试结合使用模板专业化和隐式转换来将模板类型分为 3 个类别:
- 可以隐式转换为字符串的类型
- 可以隐式转换为双精度的类型
- 不能隐式转换为字符串或双精度的类型
然而,在我的这次尝试中,所有可以转换为双精度或字符串的类型都以 T 类型的默认情况结束。
template<>
void Foo(std::string s)
{
//can be converted to a string
}
template<>
void Foo(double d)
{
//can be converted to a double
}
template<typename T>
void Foo(T t)
{
//cannot be converted to a string or a double
}
struct Other {};
int main()
{
Foo("bar");// creates Foo(const char*) instead of converting to string
Foo(1);// creates Foo(int) instead of converting to double
Other o
Foo(o);// creates Foo(Other)
}
另一方面,如果模板被移除,隐式转换仍然有效,但代价是无法处理“两种”类型。
void Foo(std::string s)
{
//can be converted to a string
}
void Foo(double d)
{
//can be converted to a double
}
struct Other {};
int main()
{
Foo("bar");// const char* -> std::string
Foo(1);// int -> double
Other o
Foo(o);// No overload available for this type
}
有没有办法在创建新的模板化函数之前优先考虑隐式转换到现有的专用模板?或者也许我应该以完全不同的方式来解决这个问题?
【问题讨论】:
-
您可以使用 SFINAE:en.cppreference.com/w/cpp/language/sfinae。
标签: c++ template-specialization overload-resolution