I ran across a compile error in clang with this code. I don’t see any problem with it and it works in msvc and gcc. Am I missing something or is it a clang bug?
#include <iostream>
#include <string>
#include <type_traits>
constexpr bool do_tests()
{
// prints error message at runtime if test is false
auto verify = [](bool test, std::string message = "error") {
if (!std::is_constant_evaluated() && !test)
std::cout << message << '\n';
return test;
};
return verify(1 == 1, "test");
};
int main()
{
constexpr bool b = do_tests();
std::cout << b << '\n';
}
Inexplicable error message from clang:
basic_string.h:356:10: note: assignment to member ‘_M_local_buf’ of union with no active member is not allowed in a constant expression
>Solution :
There is no problem with the code and Clang also compiles it correctly if you use libc++ (-stdlib=libc++). Compiler explorer by default uses libstdc++ for Clang (-stdlib=libstdc++). There simply seems to be a compatibility issue between the two. My guess is that libstdc++ is implementing the constexpr string in a way that is technically not allowed in constant expressions, but GCC tends to be less strict in that regard than Clang is, so that Clang fails with the implementation while GCC doesn’t have a problem with it.
If I find a bug report on either the libstdc++ side or Clang side I will add it here.