Is it possible to use std :: string in constexpr?

Using C ++ 11, Ubuntu 14.04, GCC default tool binding.

This code does not work:

constexpr std::string constString = "constString"; 

error: type 'const string {aka const std :: basic_string} of constexpr variable' constString is not a literal ... because ... 'Std :: basic_string has a nontrivial destructor

Is it possible to use std::string in constexpr ? (apparently no ...) If yes, then how? Is there an alternative way to use a character string in constexpr ?

+136
stdstring c ++ 11 constexpr
Nov 25. '14 at 9:44
source share
3 answers

No, and your compiler has already given you an exhaustive explanation.

But you could do this:

 constexpr char constString[] = "constString"; 

At run time, this can be used to create std :: string if necessary.

+133
Nov 25 '14 at 10:10
source share

In C ++ 17, you can use string_view :

 using namespace std::string_view_literals; constexpr std::string_view sv = "hello, world"sv; 
+109
Apr 11 '17 at 2:22 on
source share

Since the problem is a non-trivial destructor, therefore, if the destructor is removed from std::string , you can define an instance of constexpr this type. Like this

 struct constexpr_str { char const* str; std::size_t size; // can only construct from a char[] literal template <std::size_t N> constexpr constexpr_str(char const (&s)[N]) : str(s) , size(N - 1) // not count the trailing nul {} }; int main() { constexpr constexpr_str s("constString"); // its .size is a constexpr std::array<int, s.size> a; return 0; } 
+16
Jun 17 '16 at 8:35
source share



All Articles