constexpr构造函数和函数

时间:2015-06-27 09:45:22

标签: c++ constructor c++14 constexpr

我有这个类的encrypted_string,它应该在编译时加密字符串。我遇到的问题是我不能在构造函数中调用'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;
}

我正在使用'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])... } { }

我做错了什么,或者是不可能在constexpr构造函数中调用constexpr函数? 根据我对constexpr构造函数的理解,它应该是可能的。

1 个答案:

答案 0 :(得分:2)

根据https://gcc.gnu.org/projects/cxx1y.html,C ++ 14 constexpr支持直到GCC 5才会实现。

因此,即使使用-std=c++14,GCC 4.9.2也只支持C ++ 11 constexprs,它包含一个产生返回值的语句。 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;
}