C++ constexpr构造函数和函数

C++ constexpr构造函数和函数,c++,constructor,c++14,constexpr,C++,Constructor,C++14,Constexpr,我有一个加密的字符串类,它应该在编译时加密字符串。我遇到的问题是,我不能在构造函数中调用'encrypt'成员函数,但是如果我将加密放在构造函数中,它就会工作 template<typename I> class encrypted_string; template<size_t... I> class encrypted_string<std::index_sequence<I...>> { private: std::array<

我有一个加密的字符串类,它应该在编译时加密字符串。我遇到的问题是,我不能在构造函数中调用'encrypt'成员函数,但是如果我将加密放在构造函数中,它就会工作

template<typename I>
class encrypted_string;

template<size_t... I>
class encrypted_string<std::index_sequence<I...>>
{
 private:
  std::array<char, sizeof...(I)> buf;

  constexpr char encrypt(char c) const { return c ^ 0x41; }

 public:
  constexpr encrypted_string(const char* str)
  : buf { (str[I] ^ 0x41)... } { } // Works
  //: buf { this->encrypt(str[I])... } { } // Error
};

#define enc(str) encrypted_string<std::make_index_sequence<sizeof(str)>>(str)

int main()
{
  // Ensures compile time evaluation
  constexpr auto s = enc("Test");

  return 0;
}
模板
类加密的字符串;
模板
类加密字符串
{
私人:
std::阵列buf;
constexpr char encrypt(char c)const{return c^0x41;}
公众:
constexpr加密字符串(const char*str)
:buf{(str[I]^0x41)…}{}//Works
//:buf{this->encrypt(str[I])…}{}//错误
};
#定义enc(str)加密字符串(str)
int main()
{
//确保编译时评估
constexpr auto s=enc(“测试”);
返回0;
}
我正在使用“g++encrypted_string.cpp-std=c++14-o encrypted_string”进行编译,我的gcc版本是4.9.2

我遇到的错误并没有告诉我多少:

encrypted_string.cpp:17:13: note: ‘constexpr encrypted_string<std::integer_sequence<long unsigned int, _Idx ...> >::encrypted_string(const char*) [with long unsigned int ...I = {0ul, 1ul, 2ul, 3ul, 4ul}]’ is not usable as a constexpr function because:
constexpr encrypted_string(const char* str) : buf { this->encrypt(str[I])... } { }
encrypted_string.cpp:17:13:注意:'constexpr encrypted_string::encrypted_string(const char*)[带长无符号int…I={0ul,1ul,2ul,3ul,4ul}]'不能用作constexpr函数,因为:
constexpr加密的字符串(constchar*str):buf{this->encrypt(str[I])…}{
我是做错了什么,还是不能在constexpr构造函数中调用constexpr函数? 根据我对constexpr构造函数的理解,这应该是可能的。

根据,C++14 constexpr支持直到GCC 5才实现

因此,GCC4.9.2即使使用
-std=c++14
,也只支持c++11 constexpr,它包含一条生成返回值的语句。MSVC 2015 RC具有相同的限制

constexpr even(int n) { return (n & 1) == 0; } // valid c++11/14
constexpr even(int n) { return (n & 1) ? true : false; } // valid c++11/14
constexpr even(int n) { // valid c++14, not valid c++11
    if ((n & 1) == 0)
        return true;
    return false;
}

constexpr
是在编译时计算的,所以我猜调用作为类实例一部分的方法并不是正确的有效请求。我不确定这一点,但至少对我来说是有意义的。在gcc 5.1中工作良好C++14松弛常量表达式在gcc>=5中实现,参见C++11规则,构造函数体中可能没有任何代码(只有typedef、静态断言等,没有潜在的运行时代码)。将成员函数设置为
静态
或非成员。感谢您的回答,我能够在gcc 4.9上编译它,将加密函数更改为
静态
,正如Orient所指出的那样。我更新到gcc 5.1,现在它可以正常工作,没有任何修改。