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

あります)、およびconstexprコンストラクタです。構造体が<code>constexpr static</code>定数定義をコンパイルすることができないタイプの非リテラル

なぜコードはコンパイルされませんか?

また、あなたはまだ完全に宣言されていないタイプをインスタンス化しているので、それが必要で、

constexpr rgb_color rgb_color::black; 
+0

constexpr static rgb_color black(0、0、0); 'を実行すると機能しますか? – Sean

+0

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

+0

リンクには「cv-qualified(C++ 17)」の候補があります。あなたのコンパイラはここではC++ 14のルールで動作しているかもしれません。 – MSalters

答えて

14

これは動作しないように、.ccファイルにconstexpr staticメンバーを定義することです(あなたは達していません閉じ括弧とセミコロンはまだあるので、rgb_colorは依然として不完全な型です)。

あなたは多分、自分の名前空間で、クラスのあなたの定数を宣言することでこの問題を回避することができます

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

なぜこれを?すなわち -

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'は' constexpr'ではありません – chi

+0

@chi Trueです。この場合、 'constexpr'のメリットは何ですか? – ZDF

+0

定数式を必要とする式では機能しません。例えば、 'constexpr auto dummy = rgb_color :: black {}'などです。 – edmz

3

あなたはstatic constexpr関数にblackwhiteを作ることができるはずです。これは「名前付きコンストラクタイディオム」の例です。

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); } 
}; 
関連する問題