Skip to content

constexpr string from constexpr string_view is not always a constant expression #142144

Closed as duplicate of#73232
@fekir

Description

@fekir

Consider following program, which compiles with gcc and msvc

#include <string_view>
#include <string>

template <typename T>
constexpr int foo() {
  constexpr auto test = std::string_view( "test" );

  static_assert(test.size() >1);
  static_assert(std::string(test).size() >1); // should not fail
  return 0;
}


int bar(){
    return foo<int>();
}

With clang it fails to compile with "error: static assertion expression is not an integral constant expression".

Strangely, adding a local char array and a static_assert, changes the behavior

This code still fails to compile

#include <string_view>
#include <string>

template <typename T>
constexpr int foo() {
  constexpr auto test = std::string_view( "test" );
  constexpr char test2[] = "test";

  static_assert(test.size() >1);
  static_assert(std::string(test).size() >1); // should still not fail
  static_assert(std::string(test2).size() >1);
  return 0;
}


int bar(){
    return foo<int>();
}

This one compiles:

#include <string_view>
#include <string>

template <typename T>
constexpr int foo() {
  constexpr auto test = std::string_view( "test" );
  constexpr char test2[] = "test";

  static_assert(test.size() >1);
  static_assert(std::string(test2).size() >1);
  static_assert(std::string(test).size() >1); // success
  return 0;
}


int bar(){
    return foo<int>();
}

live demo: https://godbolt.org/z/KK1WjajPq

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:frontendLanguage frontend issues, e.g. anything involving "Sema"constexprAnything related to constant evaluationduplicateResolved as duplicatelibstdc++GNU libstdc++ C++ standard library

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions