【问题标题】:Mark function as noexcept based on template argument根据模板参数将函数标记为 noexcept
【发布时间】:2020-03-10 20:06:53
【问题描述】:

获取此代码:

template <class T>
void my_func() { T::some_method(); }

int main() {
    std::cout << (noexcept(my_func<SomeClass>()) ? "noexcept" : "can throw") << std::endl;
    return 0;
}

这将始终打印出my_func() 可以抛出,即使SomeClass::some_method() 被标记为noexcept。 (至少使用 gcc 7.4.0 和 -std=c++17)

有没有一种实用的方法可以让编译器根据模板参数检测函数是否为noexcept

我能想到的唯一一个是使用std::enable_if

template <class T>
std::enable_if_t<true == noexcept(T::some_method())>
my_func() noexcept { T::some_method(); }

template <class T>
std::enable_if_t<false == noexcept(T::some_method())>
my_func() { T::some_method(); }

但占用空间大,导致代码重复。

【问题讨论】:

    标签: c++ templates noexcept


    【解决方案1】:

    noexcept 规范有一个采用布尔值的版本。​​

    template <class T>
    void my_func() noexcept(noexcept(T::some_method())) { T::some_method(); }
    

    现在它将有条件地为 noexcept,基于表达式 T::some_method()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多