在 decltype 中使用命名空间
Using namespace inside decltype
我有一个函数看起来差不多是这样的:
template<class C> auto f(C const& c) -> decltype(begin(c)){
using std::begin;
return begin(c);
}
函数体利用了“using
and use”习语和
感谢 decltype
,如果 return 类型无效,将 SFINAE。
但是一般来说它并不完美,因为我无法告诉 decltype
为 begin
.
声明 using std
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 中有一个有趣的语言扩展 ("expression statements"),它很有前途,但它在函数体之外不起作用(就像在未计算的上下文中不允许使用 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...
}
您可以委托给启用 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);
}
我有一个函数看起来差不多是这样的:
template<class C> auto f(C const& c) -> decltype(begin(c)){
using std::begin;
return begin(c);
}
函数体利用了“
using
and use”习语和感谢
decltype
,如果 return 类型无效,将 SFINAE。
但是一般来说它并不完美,因为我无法告诉 decltype
为 begin
.
using std
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
.
在 GCC 中有一个有趣的语言扩展 ("expression statements"),它很有前途,但它在函数体之外不起作用(就像在未计算的上下文中不允许使用 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...
}
您可以委托给启用 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);
}