Ora*_*lar 4 c++ templates c++98
I know I cannot use a namespace as a template parameter. However, I'm trying to achieve behavior similar to this:
template <typename T>
void foo(T::X* x)
{
T::bar(x);
}
Run Code Online (Sandbox Code Playgroud)
Except T is a namespace rather than a struct or a class. What is the best way to achieve the most similar result to what I am expecting?
Sto*_*ica 12
除了T是名称空间,而不是结构或类。实现与我期望的结果最相似的结果的最佳方法是什么?
完全不提T。
template <typename X>
void foo(X* x)
{
bar(x);
}
Run Code Online (Sandbox Code Playgroud)
ADL将始终从X定义的名称空间获取重载。让机制发挥作用。
现在,如果您要问如何使编译器支持 ADL提供的功能,那么所有这些都是关于操纵重载解析的。我们可以通过限制常规不合格名称查找所选择的内容来做到这一点:
namespace foo_detail {
void bar(...);
template<typename X>
void foo_impl(X* x) {
bar(x);
}
}
template <typename X>
void foo(X* x)
{
foo_detail::foo_impl(x);
}
Run Code Online (Sandbox Code Playgroud)
当调用foo_detail::foo_impl试图解决时bar,两阶段查找中的第一阶段将提取C变量参数函数。现在查找停止,不再查找任何封闭的名称空间。这意味着只有ADL可以提供更多的候选对象。由于重载解析是如何工作的,因此像我们添加的C样式变量自变量函数将比ADL找到的匹配项更差。
这是所有工作的现场示例。