我有一个问题,我想提供一个函数foo
的通用版本,它只能在绝对没有其他匹配调用时应用。如何修改以下代码,使last_resort::foo
与derived::type
比base::foo
更糟?我想找到一个解决方案,它不涉及修改bar
的定义,它将保留last_resort::foo
参数的类型。如何在ADL期间将函数模板设置为最低优先级?
#include <iostream>
namespace last_resort
{
template<typename T> void foo(T)
{
std::cout << "last_resort::foo" << std::endl;
}
}
template<typename T> void bar(T)
{
using last_resort::foo;
foo(T());
}
namespace unrelated
{
struct type {};
}
namespace base
{
struct type {};
void foo(type)
{
std::cout << "base::foo" << std::endl;
}
}
namespace derived
{
struct type : base::type {};
}
int main()
{
bar(unrelated::type()); // calls last_resort::foo
bar(base::type()); // calls base::foo
bar(derived::type()); // should call base::foo, but calls last_resort::foo instead
return 0;
}
这是真的,但我想知道是否有办法通过用默认值增加一些额外参数来将“隐藏”转换引入到foo中? –
我不认为它会起作用。根据我所能说的,你能得到的“最好”是一种模糊性,因此编译失败。但也许,我也错过了一些东西。 – sellibitze
该解决方案似乎是装饰'''last_resort :: foo''的返回类型,类似'''disable_if_foo_exists :: type''',它将使用SFINAE来检查一个免费的'''foo '''功能。如果存在,'''last_resort :: foo'''将从超载集中移除。 –