c++visual-studiostatic-assertstdarray

Cannot define an `std::array` with `std::string` argument in Visual C++


This code builds successfully with Clang 20.1.10 and with GCC 15.1, but not with Microsoft Visual C++ 2022 version 17.14.0:

#include <array>
#include <string>

int main()
{
    static constexpr std::array<std::string, 3> as{ "a", "bb", "ccc" };

    static_assert(as[2] == "ccc");
}

The error is:

Code: C2131
Description: expression did not evaluate to a constant

Can I make this code work with Visual C++?

Who is on the right side? GCC and Clang or Visual C++?


Solution

  • Posting as an answer instead of a comment since it's presumably (likely/hopefully) the following issue:

    Visual C++ does not accept constexpr string while gcc can

    MSFT Bot claims it was fixed at the above link and a quick test shows it is (in MSVC 19.34, VS 17.4, though you'ld have to check the exact build and revision numbers, assuming they're not zero), but I can't find any official reference to the fix in their actual release notes for those versions (after a quick search only). FYI you may also want to check out the the C++ constants __cpp_lib_constexpr_string and __cpp_lib_constexpr_dynamic_alloc. In MSVC they seem to have been #defined starting in MSVC 19.29, VS 16.11 (though again, would have to check the exact build and revision numbers but your particular version is well ahead of it anyway).

    Jardod42 also makes a very good point about SSO for larger strings (yours are easily short enough) though IMHO it completely violates the point of having a C++ standard (not really a standard if you can't write standardized/portable code that might fail to compile because of an implementation issue like SSO, but I digress).

    Lastly, you may want to consider using std::string_view instead if suitable for your needs.