2016-04-26 17 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); 
}; 

I constexpr static definizioni costanti sicuro per compilare:Struct è non letterale tipo

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

Tuttavia secondo http://en.cppreference.com/w/cpp/concept/LiteralType, const rgb_color dovrebbe essere un tipo letterale, perché ha solo tipi letterali come membri di dati (std::uint8_t) e il costruttore constexpr.

Perché il codice non viene compilato?

Inoltre, è necessario definire le constexpr static membri in un file .cc, come

constexpr rgb_color rgb_color::black; 
+0

Funziona se si esegue 'constexpr static rgb_color black (0, 0, 0);'? – Sean

+0

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

+0

Il link che hai suggerito: "possibilmente qualificato in cv (C++ 17)". Il tuo compilatore potrebbe giocare secondo le regole del C++ 14 qui. – MSalters

risposta

14

Questo non funziona, perché si sta istanziare un tipo che non è ancora pienamente dichiarata (non si è raggiunto la parentesi graffa di chiusura e punto e virgola ancora, quindi rgb_color è ancora un tipo incompleto).

È possibile aggirare il dichiarando i vostri costanti fuori della classe, forse nel proprio spazio dei nomi:

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
Perché non

questo?

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' non è' constexpr' – chi

+0

@chi True. Qual è il vantaggio di 'constexpr' in questo caso? – ZDF

+0

Che non funzionerà in espressioni che richiedono un'espressione costante. 'constexpr auto dummy = rgb_color :: black {}', per esempio. – edmz

3

Si dovrebbe essere in grado di fare black e white in static constexpr funzioni - cioè. questo è un esempio di "idioma di nome-costruttore".

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); } 
}; 
Problemi correlati