【发布时间】:2014-10-06 15:59:31
【问题描述】:
考虑以下系统:
template<typename T>
struct wrapper
{
operator T * () { return nullptr; }
};
template<typename Ret, typename T>
Ret func(T);
template<>
int func(float * in)
{
std::cout << "long";
}
template<>
long func(float * in)
{
std::cout << "int";
}
包装器的目的是允许它衰减到模板化的类型(它是该类型缓冲区的包装器)。此外,我有一组函数是模板的模板特化。这是为了规避仅基于返回类型重载时的常见错误。
但这不起作用,如下所述:
// the following should work, but doesn't because it's instantiating
// the func<ret, wrapper<float>> which doesn't exist resulting in a linker error
// instead of selecting the int func(float *) overload
wrapper<float> w;
func<int>(w);
相反,我希望这会产生编译时错误(但同样会产生链接时错误):
// the following should generate a compile-time error
// since no explicit overload for int func(int *) exists
wrapper<int> w2;
func<int>(w2);
所以理想情况下,我想禁用原始模板(如果可能的话,也许通过 sfinae?)这样重载解决方案只考虑显式特化,如果找不到匹配项,则会生成编译时错误。这个可以吗?
clang 和 msvc 之间的便携式解决方案是必须的,但我使用的是两者的最新版本。
【问题讨论】:
-
您的问题不在于重载解析,而在于模板参数推导不考虑隐式转换。
-
@P0W 因为你不能超载这两个。唯一的区别是返回类型。
-
@TC 啊,我明白了,谢谢
标签: c++ templates sfinae overload-resolution