如何解决用于Koenig查找的尾随返回类型和回退
在大多数情况下,简单成员函数的C ++ 17推断返回类型可以轻松转换为C ++ 11尾随返回类型。
例如,
中的成员函数template<typename T>
struct X
{
T a;
auto f() { return frob(a); }
};
成为
auto f() -> decltype(frob(a)) { return frob(a); }
考虑到在类主体的顶级范围内不允许使用using namespace
,您如何为以下内容编写尾随返回类型?
namespace widget
{
template<typename S>
int froz(S&&);
}
template<typename T>
struct Y
{
T b;
auto g() { using namespace widget; return froz(b); }
};
(例如,在调用std::swap
,std::begin
,std::end
时使用带有后备参数的依赖参数的查询非常普遍)
template<typename T>
struct Z
{
T container;
auto h() { using namespace std; return begin(container); }
};
解决方法
怎么样:
template<typename T>
struct Z
{
T container;
auto h() -> decltype(
[]
{
Z<T>* z;
using namespace std; return begin(z->container);
}()
) { using namespace std; return begin(container); }
};
,
这是我发现的最好的解决方法,它引入了一个助手名称空间来尽可能紧密地托管using namespace
:
namespace impl
{
using namespace std;
template<typename T>
struct Z
{
T container;
auto h() -> decltype(begin(container)) { return begin(container); }
};
}
using impl::Z;
为了不影响整个类,可以使Ayxan在辅助函数上使用decltype
的想法在C ++ 11中起作用:
namespace impl
{
using namespace std;
template<typename T>
auto begin(T&& t) -> decltype(begin(std::forward<T&&>(t)));
}
template<typename T>
struct Z
{
T container;
auto h() -> decltype(impl::begin(container)) { using namespace std; return begin(container); }
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。