gpt4 book ai didi

c++ - 在 decltype 中使用命名空间

转载 作者:太空狗 更新时间:2023-10-29 20:34:09 24 4
gpt4 key购买 nike

我有一个看起来或多或少像这样的函数:

template<class C> auto f(C const& c) -> decltype(begin(c)){
using std::begin;
return begin(c);
}
  1. 函数体利用了“using and use”惯用语和

  2. 感谢 decltype,如果返回类型无效,将 SFINAE。

但是它通常并不完美,因为我无法告诉 decltype 有一个 using std 声明用于 begin

template<class C> auto f(C const& c) -> decltype(std::begin(c))

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

有办法解决吗?

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

template<class C> auto f(C const& c) -> decltype(using std::begin; begin(c))

我认为 lambda 原则上可以工作

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

但是在 decltype 中禁止使用 lambda。


在 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...
}

最佳答案

您可以委托(delegate)给启用 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);
}

关于c++ - 在 decltype 中使用命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50456521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com