尾随 return 类型中的名称查找问题

Name lookup issue in trailing return type

以下示例说明了我的问题:

#include <iostream>
#include <string>

template <typename T>
auto func(const T& x) -> decltype(to_string(x)) {
  using std::to_string;
  return to_string(x);
}

int main() {
  std::cout << func(1);
}

我不想将 std::to_string 导入全局命名空间,我也不想使用 -> decltype(std::to_string(x)),因为这样做会禁用 ADL。显然,您不能将 using std::to_string 放在 decltype 中。那么,我应该怎么做呢?

遵从另一个命名空间;

namespace activate_adl {
  using std::to_string;
  template <typename T>
  auto func(const T& x) -> decltype(to_string(x)) {
    return to_string(x);
  }
}

template <typename T>
auto func(const T& x) -> decltype(activate_adl::func(x)) {
  return activate_dl:: func(x);
}

这允许 ADL 仍然完成,但不会污染您的全局命名空间。

在一些 std 相关函数和 ADL 中多次遇到这个问题后,我发现延迟命名空间(命名良好)是合适的替代方案。