gpt4 book ai didi

c++ - 如何在 ADL 期间使功能模板成为最低优先级?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:41:47 24 4
gpt4 key购买 nike

我有一个问题,我想提供函数 foo 的通用版本,它只能在绝对没有其他匹配的调用时应用。我如何修改以下代码,使 last_resort::fooderived::type 的匹配程度低于 base::foo?我想找到一个解决方案,它不涉及修改 bar 的定义,并且会保留 last_resort::foo 的参数类型。

#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;
}

最佳答案

这会变得很糟糕:

struct badParam { template <typename T> badParam(T t) { } };
namespace last_resort {
void foo(badParam, int dummy = 0, ...) {
std::cout << "last_resort::foo" << std::endl;
}
}

您有一个用户定义的转换、一个默认参数和一个未使用的省略号。

[编辑]

轻微的变体,为了节省 T 我将用户定义的转换移动到虚拟参数:

struct badParam { 
badParam() { }
operator int() { return 42; }
};
namespace last_resort {
template <typename T> void foo(T t, int dummy = badParam(), ...) {
std::cout << "last_resort::foo" << std::endl;
}
}

关于c++ - 如何在 ADL 期间使功能模板成为最低优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7614633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com