2

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

#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. 那么,我该怎么做呢?

4

1 回答 1

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);
}

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

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

于 2016-01-27T11:39:01.387 回答