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

Lin*_*gxi 2 c++ template-meta-programming argument-dependent-lookup trailing-return-type c++14

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

#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);
}
Run Code Online (Sandbox Code Playgroud)

我不想导入std::to_string全局命名空间,我不想-> decltype(std::to_string(x))这样做,因为这样做会禁用ADL.很显然,你不能把using std::to_stringdecltype.那么,我该怎么做呢?

Nia*_*all 6

推迟到另一个名称空间;

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);
}
Run Code Online (Sandbox Code Playgroud)

这样可以完成ADL,但不会污染全局命名空间.

在使用一些std相关函数和ADL 几次遇到此问题后,我发现延迟命名空间(命名良好)是合适的替代方案.