繁体   English   中英

对于类型为类模板特化的参数,ADL背后的基本原理是什么?

[英]What is the rationale behind ADL for arguments whose type is a class template specialization

我花了一些时间试图意识到为什么我的代码不能编译,我已经意识到在C ++ Argument Dependent Lookup中使用模板typename参数来确定名称查找范围。

#include <string>
#include <functional>

namespace myns {

    template<typename T>
    struct X
    {};

    template<typename T>
    auto ref(T) -> void
    {}

} // namespace myns

auto main() -> int
{
    ref(myns::X<int>{});
    ref(myns::X<std::string>{}); // error: call to 'ref' is ambiguous
}

所以前面的ref调用编译,因为对于myns::X<int>只考虑myns::ref ,而后者不编译因为它找到myns::ref()以及std::ref

我的问题是这有用吗? 我为什么需要这个? 你有什么想法,例子吗? 现在我只能看到上面例子中的缺点,它会引入不必要的歧义。

假设您将所有内容放入您自己的命名空间,包括用户定义的类,以及以std::vector作为参数的函数。

namespace myns {

    struct X {};

    template<typename T>
    auto my_func(const std::vector<T>&) -> void
    {}

} // namespace myns

那么你可以利用ADL也考虑提供的类型作为模板参数的事实,并写下:

my_func(std::vector<myns::X>{});

另一方面:

my_func(std::vector<int>{});        // error, can't find my_func
myns::my_func(std::vector<int>{});  // fine

回到原来的问题,这里的教训是不使用标准库中的名称,只会使代码混乱。

一句话:重用。 它允许您使用其他库中的有用组件,并且仍然应用了ADL。

例如:

namespace my_stuff {
  class my_class {
    // Something useful here
  };

  void process(std::unique_ptr<my_class> item);
}

现在,您可以自然地编写代码,就像直接使用类时一样:

process(std::make_unique<my_class>());

如果不是这种情况,您需要在自己的命名空间中推出自己的智能指针,以促进良好的编码习惯和ADL。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM