jeudi 2 février 2017

Literal Type Class in C++11/C++14

int x = 1; // Non-Constant

class A {
    public:
        int value { x };
        A( int z ) : value( x ) {}
        constexpr A() : value( 0 ) {}
};

// constexpr int function( A obj ){ return 1; }

int main(){

    int y = 2; // Non-Constant
    A obj ( y );

    // int var = function( obj );
    return 0;
}

C++11 Standard (ISO/IEC 14882:2011), Section 3.9, Paragraph 10 states (emphasis mine):

A type is a literal type if it is:

  • a scalar type; or
  • a reference type; or
  • a class type (Clause 9) that has all of the following properties:
    • it has a trivial destructor,
    • every constructor call and full-expression in the brace-or-equal-initializers for non-static data members (if any) is a constant expression (5.19),
    • it is an aggregate type (8.5.1) or has at least one constexpr constructor or constructor template that is not a copy or move constructor, and
    • it has all non-static data members and base classes of literal types; or
  • an array of literal type.

In my opinion, taking into account the bullet in bold, class A is not a literal type in C++11 because there is a constructor call (A obj ( y );) and a brace-or-equal-initializer for a non-static data member (A( int z ) : value( x ) {}) that are not constant expressions. I tried putting constexpr before the constructor definition and also assigning the constructor call to a constexpr variable to check that indeed the compiler complains because those are not constant expressions. I also tried with constructor calls like A obj { y }; or A obj = { y }; However, both Clang and GCC compile it successfully. So I am probably wrong.

  • Does anyone know why class A is a literal type?

The bullet in bold was removed in C++14 (N3652), so I understand class A is a literal type in C++14. I need to know because function is constexpr, therefore each of its parameter types shall be a literal type (C++11/C++14 Standard, Section 7.1.15, Paragraph 3).

Aucun commentaire:

Enregistrer un commentaire