在decltype中使用命名空间

alf*_*lfC 3 c++ decltype using-declaration argument-dependent-lookup c++11

我有一个看起来或多或少像这样的功能:

template<class C> auto f(C const& c) -> decltype(begin(c)){
    using std::begin;
    return begin(c);
}
Run Code Online (Sandbox Code Playgroud)
  1. 函数的主体利用" using和使用"成语和

  2. 感谢decltypeSFINAE,如果返回类型无效.

然而,它一般来说并不完美,因为我无法告诉它decltypeusing std声明begin.

template<class C> auto f(C const& c) -> decltype(std::begin(c))
Run Code Online (Sandbox Code Playgroud)

也会不一致,例如何时decltype(c)begin属于不同的命名空间.

周围有路吗?

理想情况下,我想要类似的东西

template<class C> auto f(C const& c) -> decltype(using std::begin; begin(c))
Run Code Online (Sandbox Code Playgroud)

我认为lambda原则上可以工作

template<class C> auto f(C const& c) -> decltype([&]{using std::begin; return begin(c)})
Run Code Online (Sandbox Code Playgroud)

但是内部禁止使用lambdas decltype.


在GCC中有一个有趣的语言扩展("表达式语句")是有希望的,但是它不能在函数体外工作(与未评估的上下文中不允许使用lambda). 否则它将是一个解决方案.

template<class C> auto g(C const& c) 
->decltype(({using std::begin; begin(c);})){ // ...that doesn't work here
    return(({using std::begin; begin(c);})); // gcc extesion...
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*ian 5

您可以委派给启用ADL的命名空间

namespace detail
{
    using std::begin;
    template<class C> auto f(C const& c) -> decltype(begin(c)){
        return begin(c);
    }
}

template<class C> auto f(C const& c) -> decltype(detail::f(c)){
    return detail::f(c);
}
Run Code Online (Sandbox Code Playgroud)

  • 或者只是`使用detail :: f`. (2认同)