C++模板编程中如何检测一个变量是否为编译期常量?

利用标准中的特性:

  1. core constant expression一定是noexcept的(虽然反过来不成立)
  2. 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值