我想要一个constexpr从constexpr函数计算的值(即编译时常量).我想要将这两个作用于类的命名空间,即静态方法和类的静态成员.
我第一次写这个(对我来说)明显的方式:
class C1 {
  constexpr static int foo(int x) { return x + 1; }
  constexpr static int bar = foo(sizeof(int));
};
g++-4.5.3 -std=gnu++0x 对此说:
error: ‘static int C1::foo(int)’ cannot appear in a constant-expression
error: a function call cannot appear in a constant-expression
g++-4.6.3 -std=gnu++0x 抱怨:
error: field initializer is not constant
好吧,我想,也许我必须把事情从课堂上移开.所以我尝试了以下方法:
class C2 {
  constexpr static int foo(int x) { return x + 1; }
  constexpr static int bar;
}; …这段代码可以在g ++(coliru)中很好地编译,但是在MSVC(Godbolt和我的VS2017)中却不能。
#include <type_traits>
#include <iostream>
template<class T> void f(){
    constexpr bool b=std::is_same_v<T,int>; //#1
    auto func_x=[&](){
        if constexpr(b){ //#error
        }else{
        }
    };
    func_x();
}
int main(){
    f<int>();
}
(6):错误C2131:表达式未求值为常数
(6):注意:失败是由于在其生命周期之外读取变量导致的
(6):注意:请参见'this'的用法
哪一个(g ++或MSVC)错了?“ 请参阅'this'的用法 ” 
是什么??this
在保留编译时保证的同时如何解决呢?
在我的真实情况下,b (#1)一个复杂的语句取决于其他一些constexpr变量。     
我对static constexprC++ 11中的成员变量有一些疑惑.
template<typename T>
struct cond_I
{ static constexpr T value = 0; }; 
// specialization 
template<typename T>
struct cond_I< std::complex<T> >
{ static constexpr std::complex<T> value = {0,1}; }; 
cout << cond_I<double>::value << endl;            // this works fine
cout << cond_I< complex<double> >::value << endl; // linker error
但是,如果我添加以下行,first.hpp一切正常.
template<typename T1> 
constexpr std::complex<T1> cond_I< std::complex<T1> >::value;
我理解的(我可能是错的)是,cond_I< std::complex<double> >::value需要一个定义,但在前一种情况下它只有声明.但那又怎么样cond_I<double>::value?为什么它不需要定义?
再次,在另一个头文件中second.hpp,我有:
// empty struct
template<typename T> …