gpt4 book ai didi

c++ - 可以使用尾随返回类型进行条件重载吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:19:35 25 4
gpt4 key购买 nike

假设您尝试执行以下操作:

template</* args */>
typename std::enable_if< /*conditional*/ , /*type*/ >::type
static auto hope( /*args*/) -> decltype( /*return expr*/ )
{
}

是否可以将条件包含/重载 ( std::enable_if ) 与尾随返回类型 ( auto ... -> decltype() ) 结合起来?

我对使用预处理器的解决方案不感兴趣。我总是可以做类似的事情

#define RET(t) --> decltype(t) { return t; }

并将其扩展为也采用整个条件。相反,我感兴趣的是语言是否支持它而不使用返回类型的另一个特征,即 ReturnType<A,B>::type_t或函数体中使用的任何内容。

最佳答案

trailing-return-type 与普通返回类型没有太大区别,只是它在参数列表和 cv-/ref-qualifiers 之后指定。此外,它不一定需要 decltype,普通类型也可以:

auto answer() -> int{ return 42; }

现在你应该知道你的问题的答案是什么了:

template<class T>
using Apply = typename T::type; // I don't like to spell this out

template</* args */>
static auto hope( /*args*/)
-> Apply<std::enable_if</* condition */, decltype( /*return expr*/ )>>
{
}

虽然我个人更喜欢只使用 decltype 和表达式 SFINAE,只要条件可以表示为表达式(例如,您可以在特定类型的对象上调用函数):

template<class T>
static auto hope(T const& arg)
-> decltype(arg.foo(), void())
{
// ...
}

关于c++ - 可以使用尾随返回类型进行条件重载吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11866291/

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