Am I confused about the constexpr function?

In C ++ Primer, fifth edition, §6.5.2:

Function A is constexprdefined as any other function, but must comply with certain restrictions: The return type and type of each parameter in must be a literal type (§2.4.4, p. 66), and the function body must contain exactly one return statement

but another sentence in this chapter (p. 239):

The constexpr function is allowed to return a value that is not a constant

// scale(arg) is a constant expression if arg is a constant expression
constexpr size_t scale(size_t cnt) { return new_sz() * cnt; }

Is this a controversial resume? I'm confused. scaleIs the return type a literal type?
Update: what's the difference between literal type and constant?

+4
source share
3

. , "", , constexpr . ++ 11:

§7.1.5/7 constexpr , constexpr , constexpr .

+6

, , , constexpr .

constexpr , , , :

// scale(arg) is a constant expression if arg is a constant expression

:

int arr[scale(2)]; // ok: scale(2) is a constant expression
int i = 2; // i is not a constant expression
int a2[scale(i)]; // error: scale(i) is not a constant expression

++ ( C99) , , scale .

, , :

  • void ( ++ 14) ( constexpr void)
  • , , , , std:: nullptr_- t cv- )
  • , :
    • ,
    • -
      • constexpr (, ),
    • .
+8

constexpr , , , ()

int a1 = 5;
std::array<int, a1> arr1; // error, a is variable

const int a2 = 5;
std::array<int, a2> arr2; // OK

int f1() { return 3; }
std::array<int, f1()> arr3; // error, compiler doesn't know it is const 3

constexpr int f2() { return 3; }
std::array<int, f2()> arr4; // OK

:

constexpr int f3() { return f1() + 1; } // error, f1 is not constexpr

constexpr int f4() { return f2() + 1; } // OK
std::array<int, f4()> arr5; // OK

: ( ), , ( ).

constexpr std::string f5() { return "hello"; } // error, 
                   // std::string is not literal type

constexpr const std::string& f6() { 
  static const std::string s = "hello";
  return s;
}

template<const std::string& s> SomeClass { ... };
SomeClass<f6()> someObject;
0

All Articles