Код: Выделить всё
std::string("a") + "b"
Создание строки посредством неявного преобразования (
Код: Выделить всё
string A = "ab"
Код: Выделить всё
string B = std::string("ab")
Как ни странно, предварительное выполнение операции сложения в функции constexpr также работает нормально (
Код: Выделить всё
string C() { return std::string("a") + "b"; }
Я не уверен, почему приведенные выше решения компилируются успешно, но использование «+» непосредственно в объявлении переменной каким-то образом делает переменную непригодной для использования в дальнейших constexprs.
См. пример кода ниже:
Код: Выделить всё
#include
#include
static constexpr std::string A = "ab";
static constexpr std::string _A = A; //compiles
static constexpr std::string B = std::string("ab");
static constexpr std::string _B = B; //also compiles
static constexpr std::string C() { return std::string("a") + "b"; }
static constexpr std::string _C = C(); //also compiles
static constexpr std::string D = std::string("a") + "b";
static constexpr std::string _D = D; //error: the value of ‘D’ is not usable in a constant expression
int main() {
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/79221709/constexpr-string-not-usable-in-constant-expression-if-string-created-with-additi[/url]