4

First of all, I assume with C++20 we have a constexpr std::string in C++20. If that is the case, it should be possible to write something like:

struct MyType { constexpr MyType(int n_):n{n_}{}; int n; };

template < auto a > struct Something {};
template <> struct Something< MyType{1} > { void Do() { std::cout << "Special One" << std::endl;} };
template <> struct Something< MyType{2} > { void Do() { std::cout << "Super Two" << std::endl;} };


int main()
{
    Something<MyType{1}> s; // works fine as expected
    s.Do();

    Something< std::string("Hallo")> s2; // did not work. See error message below
}

But gcc 10.1 complains, that std::string is not a literal type because the destructor is not constexpr. But if I understand the current standard correctly, std::string should be "fully" constexpr.

I am wrong? Or is the current STL from gcc not c++20 "ready"?

Full error message from gcc 10.1 ( same with current g++ trunk ).

/usr/include/c++/10/bits/basic_string.h:77:11: note: 'std::__cxx11::basic_string<char>' is  not literal because:
   77 |     class basic_string
      |           ^~~~~~~~~~~~
/usr/include/c++/10/bits/basic_string.h:77:11: note:   'std::__cxx11::basic_string<char>' does not have 'constexpr' destructor
Klaus
  • 24,205
  • 7
  • 58
  • 113
  • Yes we don't. Look at https://en.cppreference.com/w/cpp/string/basic_string and search for C++20 – sehe Jul 11 '20 at 17:51
  • @sehe Can't catch your point... I see no constructor nor destructor tagged with c++20. But cppreference is not the standard and maybe not "up to date". But the linked p0980r1.pdf tells us, that "all" is constexpr... – Klaus Jul 11 '20 at 17:58
  • `constexpr std::string s{"Hallo"};` won't compile with gcc https://gcc.godbolt.org/z/hWdPE7 – Aykhan Hagverdili Jul 11 '20 at 18:00
  • 2
    Lots of compilers aren't fully up to date even though they have some C++20. – QuentinUK Jul 11 '20 at 18:01
  • Cppreference page on [`std::allocator::allocate`](https://en.cppreference.com/w/cpp/memory/allocator/allocate) has this interesting bit: *"In order to use this function in a constant expression, the allocated storage must be deallocated within the evaluation of the same expression."* So compile-time allocations must be deallocated at compile-time. I'm not sure if `std::string` is supposed to have `constexpr` on its methods, but it probably wouldn't help in this case because of that. – HolyBlackCat Jul 11 '20 at 18:03
  • 1
    @QuentinUK: Quite clear, early times to use it. I only want to know if it "should" work. If it is currently not working, is not my question, I saw it :-) – Klaus Jul 11 '20 at 18:03
  • @HolyBlackCat indeed. Courtesy of inlining, escape analysis and §18.6.1.1/2 "An implementation is allowed to omit a call to a replaceable global allocation function". So you might not need constexpr in the first place. – sehe Jul 11 '20 at 19:02

0 Answers0