我如何静态地断言static_cast是noexcept?

问题描述 投票:3回答:1

我有一个漏斗来执行从任何类型到特定类型的静态转换,它是这样定义的。

template <typename T_Out>
struct cast_to {
    template <typename T_In>
    T_Out operator()(T_In&& value) const noexcept {
        return static_cast<T_Out>(value);
    }
};

现在,我想把这个漏斗的使用限制在那些被隐式或显式声明为 noexcept. 这个想法是在 operator() 函数。到目前为止,我已经用两个conexpr表达式进行了尝试。

std::is_nothrow_constructible<T_Out, decltype(value)>::value

noexcept(static_cast<T_Out>(value))

两种方法似乎都能如我所料的那样工作(实际上,我看到第一个检查也包括另一个,至少在GCC上)。我应该选择哪种方法?有更好的选择吗?

c++ static-cast static-assert noexcept
1个回答
1
投票

这取决于你想在技术上有多正确。正如你所说,这两个选项都达到了预期的目标--防止编译。区别在于

  • std::is_nothrow_constructible 测试将总是评估为真或假,使你的断言通过或失败。

  • noexcept测试要么评估为true,要么评估为false,或者如果你传递的参数根本没有转换,则会导致编译内部static_cast检查失败。

我会选择下面的一种。

  1. SFINAE检查std::is_nothrow_constructible。
  2. SFINAE检查std::is_constructible,static_assert检查noexcept。

选项2可能有更好的诊断方法,但选项1可能在技术上更正确。这是个人的喜好。

© www.soinside.com 2019 - 2024. All rights reserved.