简体   繁体   English

GCC <= 10 的模板 ADL 的替代方案

[英]Alternative to template ADL for GCC <= 10

Consider the following valid C++20 code:考虑以下有效的 C++20 代码:

#include <utility>

namespace foo
{
  template<typename... Args>
  struct tuple : Args... { };

  template<std::size_t N, typename... Args>
  auto get(tuple<Args...>) { return 0; }
}

namespace bar
{
  template<typename... Args>
  struct tuple : Args... { };

  template<std::size_t N, typename... Args>
  auto get(tuple<Args...>) { return 0; }
}

template<class Tuple, std::size_t... N>
auto for_each(Tuple& args, std::index_sequence<N...>) {
  (get<N>(args), ...);
}

int main()
{
  struct test { };
  foo::tuple<test> t;
  for_each(t, std::make_index_sequence<1>());
}

Here, get<N> is able to be resolved through ADL thanks to a C++20 addition ( http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0846r0.html )在这里,由于添加了 C++20( http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/p0846r0.html ), get<N>能够通过 ADL 解决

My question is, what are the workarounds to this before C++20, which do not require the method for_each to know about the foo and bar namespaces?我的问题是,在 C++20 之前有哪些解决方法,不需要方法for_each来了解foobar命名空间?

I'd be happy with anything that works starting from GCC 8.我会对从 GCC 8 开始的任何工作感到满意。

You can add a dummy function and leave it without definition to make the compiler happy.您可以添加一个虚拟 function 并使其不定义以使编译器满意。

When the template is instatiated the right methods will be found through ADL.当模板被实例化时,将通过 ADL 找到正确的方法。

#include <utility>
#include <tuple>

namespace foo
{
  template<typename... Args>
  struct tuple : Args... { };

  template<std::size_t N, typename... Args>
  auto get(tuple<Args...>) { return 0; }
}

namespace bar
{
  template<typename... Args>
  struct tuple : Args... { };

  template<std::size_t N, typename... Args>
  auto get(tuple<Args...>) { return 0; }
}

template <typename... T>
struct Dummy;

template <std::size_t N, typename... Args>
auto get(Dummy<Args...>);

template<class Tuple, std::size_t... N>
auto for_each(Tuple& args, std::index_sequence<N...>) {
  (get<N>(args), ...);
}

int main()
{
  struct test { };
  foo::tuple<test> t;
  for_each(t, std::make_index_sequence<1>());
}

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

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