Fou*_*met 3 c++ templates noexcept
采取以下代码:
template <class T>
void my_func() { T::some_method(); }
int main() {
std::cout << (noexcept(my_func<SomeClass>()) ? "noexcept" : "can throw") << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
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(); }
Run Code Online (Sandbox Code Playgroud)
但是,这会占用大量空间并导致代码重复。
Sto*_*ica 10
noexcept 规格有一个采用布尔值的版本。
template <class T>
void my_func() noexcept(noexcept(T::some_method())) { T::some_method(); }
Run Code Online (Sandbox Code Playgroud)
现在,基于表达式它将有条件地例外T::some_method()。