Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returning constexpr does not compile

Why doesn't this compile:
Could there be a problem with a string as a return type?

constexpr std::string fnc()
{
    return std::string("Yaba");
}
like image 380
smallB Avatar asked Oct 15 '11 16:10

smallB


People also ask

Can a function return constexpr?

Unlike const , constexpr can also be applied to functions and class constructors. constexpr indicates that the value, or return value, is constant and, where possible, is computed at compile time.

Is constexpr always evaluated at compile time?

A constexpr function that is eligible to be evaluated at compile-time will only be evaluated at compile-time if the return value is used where a constant expression is required. Otherwise, compile-time evaluation is not guaranteed.

When to use #define vs constexpr?

#define directives create macro substitution, while constexpr variables are special type of variables. They literally have nothing in common beside the fact that before constexpr (or even const ) variables were available, macros were sometimes used when currently constexpr variable can be used.

Can a function parameter be constexpr?

The variable declaration is not marked constexpr . The function parameter isn't constexpr . The function itself isn't marked constexpr , and it's not an immediate function. But arbitrarily we can use the value in a constexpr context.


1 Answers

The constructor of std::string that takes a pointer to char is not constexpr. In constexpr functions you can only use functions that are constexpr.

like image 132
R. Martinho Fernandes Avatar answered Oct 09 '22 08:10

R. Martinho Fernandes