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

Name lookup issue in trailing return type

本文关键字:查找 问题 返回类型      更新时间:2023-10-16

下面的例子说明了我的问题:

#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 中多次遇到此问题后,我发现延迟命名空间(名称良好)是合适的替代方案。