请看下面的代码:
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(); }但它占用大量空间,并导致代码重复。
发布于 2019-11-15 03:00:52
noexcept规范有一个接受布尔值的版本。
template <class T>
void my_func() noexcept(noexcept(T::some_method())) { T::some_method(); }现在,基于表达式T::some_method(),它将有条件地设置为noexcept。
https://stackoverflow.com/questions/58864001
复制相似问题