利用标准中的特性:
- core constant expression一定是noexcept的(虽然反过来不成立)
- constexpr function当接受core constant expression的时候调用它的表达式也是一个core constant expression.
需要注意的是,这里提到的特性1目前据我所知只有GCC的实现是正确的.Clang没有正确实现该特性,在进行noexcept性质的计算的时候不会考虑要计算的表达式是否是core constant expression:
noexcept should check whether the expression is a constant expression
以下符合标准的代码已使用4.8.1版本开始的所有GCC版本在C++11,C++14和C++1z的选项下测试通过
#include <iostream>
template <typename T>
constexpr int foo(T){
return 0;
}
class AAA{
public:
explicit constexpr AAA(int) noexcept{}
AAA(const AAA &) noexcept(false){
throw 1;
}
AAA& operator=(const AAA &) noexcept(false){
throw 1;
return *this;
}
};
constexpr AAA bar() noexcept{
return AAA(0);
}
int main(){
const int a = 5;
int b=5;
constexpr int c=2;
#define d 10
std::cout << noexcept(foo(1)) << std::endl;
std::cout << noexcept(foo(a)) << std::endl;
std::cout << noexcept(foo(b)) << std::endl;
std::cout << noexcept(foo(c)) << std::endl;
std::cout << noexcept(foo(d)) << std::endl;
std::cout << noexcept(sizeof (int)) << std::endl;
std::cout << noexcept(foo(bar())) << std::endl;
return 0;
}
1 1 0 1 1 1 1