简化 noexcept 说明符 + 尾随返回类型 + 函数体

Vai*_*Man 5 c++

想象一下编写一些通用代码:

template<class...Args>
auto do_something(Args&&...args)
        noexcept(noexcept(detail::do_something(std::forward<Args>(args)...)))
        -> decltype(detail::do_something(std::forward<Args>(args)...))
{
    return detail::do_something(std::forward<Args>(args)...);
}
Run Code Online (Sandbox Code Playgroud)

我不得不重复detail::do_something(std::forward<Args>(args)...)三遍这个长表情。

noexcept需要说明符来传播noexcept-ness。

需要尾随返回类型,因为许多标准类型特征和概念(例如invocable-families)需要知道直接上下文中的返回类型。

我知道这可以通过宏来解决。但是有没有任何 C++ 方法可以简化它,或者任何现有的工作可能有助于将来简化它?

例如,2015年写的一个答案提到了一项提案,该提案引入了noexcept(auto)但仍处于“我们认为 noexcept(auto) 的有效和合理使用是否足够重要以至于我们应该标准化它?”的状态。

康桓瑋*_*康桓瑋 5

目前,除了使用宏之外,标准中没有对此提供语言支持。但是,您可以使用BOOST_HOF_RETURNSBoost.HOF 来避免重复表达式

#include <boost/hof/returns.hpp>

namespace detail {
  template<class...Args>
  decltype(auto) do_something(Args&&...args);
};

template<class...Args>
auto do_something(Args&&...args)
  BOOST_HOF_RETURNS(
    detail::do_something(std::forward<Args>(args)...))
Run Code Online (Sandbox Code Playgroud)

演示