2016-04-26 9 views
6
struct rgb_color { 
    constexpr rgb_color(std::uint8_t nr, std::uint8_t ng, std::uint8_t nb) : 
     r(nr), g(ng), b(nb) { } 

    std::uint8_t r; // red 
    std::uint8_t g; // green 
    std::uint8_t b; // blue 

    constexpr static rgb_color black = rgb_color(0, 0, 0); 
    constexpr static rgb_color white = rgb_color(255, 255, 255); 
}; 

Die constexpr static konstanten Definitionen nicht kompilieren:Struct ist nicht-wörtlicher Typ

constexpr variable cannot have non-literal type 'const rgb_color' 

jedoch http://en.cppreference.com/w/cpp/concept/LiteralType nach, const rgb_color sollte ein wörtlicher Typ sein, weil es nur wörtliche Typen als Datenelement hat (std::uint8_t) und der constexpr Konstruktor.

Warum kompiliert der Code nicht?

Auch ist es notwendig, die constexpr static Mitglieder in einer .cc Datei, wie

constexpr rgb_color rgb_color::black; 
+0

Funktioniert es, wenn Sie 'constexpr statische rgb_color schwarz (0, 0, 0);'? – Sean

+0

Nein: http://coliru.stacked-crooked.com/a/f7915407bb464659 – tmlen

+0

Der Link, den Sie geben, hat einen Vorschlag: "möglicherweise cv-qualifiziert (C++ 17)". Ihr Compiler spielt hier möglicherweise nach den C++ 14 Regeln. – MSalters

Antwort

14

Das funktioniert nicht, zu definieren, weil Sie eine Art sind Instanziierung, die noch nicht vollständig erklärt wird (Sie haben nicht erreicht die schließende Klammer und Semikolon noch, so rgb_color ist immer noch ein unvollständiger Typ).

Sie können dieses Problem umgehen, indem Sie Ihre Konstanten aus der Klasse deklariert, vielleicht in ihrem eigenen Namensraum:

namespace rgb_color_constants { 
    constexpr static rgb_color black = rgb_color(0, 0, 0); 
    constexpr static rgb_color white = rgb_color(255, 255, 255); 
} 
2

Warum diese nicht?

struct rgb_color { 
    constexpr rgb_color(std::uint8_t nr, std::uint8_t ng, std::uint8_t nb) : 
     r(nr), g(ng), b(nb) { } 

    std::uint8_t r; // red 
    std::uint8_t g; // green 
    std::uint8_t b; // blue 

    static const rgb_color black; 
    static const rgb_color white; 
}; 

const rgb_color rgb_color::black {0, 0, 0}; 
const rgb_color rgb_color::white {255, 255, 255}; 
+1

'const' ist nicht' constexpr' – chi

+0

@chi Wahr. Was nützt "constexpr" in diesem Fall? – ZDF

+0

Das funktioniert nicht in Ausdrücken, die einen konstanten Ausdruck erfordern. 'constexpr auto dummy = rgb_color :: black {}', zum Beispiel. – edmz

3

sollten Sie in der Lage sein black und white in static constexpr Funktionen zu machen - das heißt. Dies ist ein Beispiel für das "Named-Constructor-Idiom".

struct rgb_color { 
    constexpr rgb_color(std::uint8_t nr, std::uint8_t ng, std::uint8_t nb) : 
    r(nr), g(ng), b(nb) { } 

    std::uint8_t r; // red 
    std::uint8_t g; // green 
    std::uint8_t b; // blue 

    constexpr static rgb_color black() { return rgb_color(0, 0, 0); } 
    constexpr static rgb_color white() { return rgb_color(255, 255, 255); } 
}; 
Verwandte Themen