2016-12-17 25 views
4

constexprメンバ変数を使用してconstexprメンバ変数を初期化したいが、コンパイルしなかった。私はクラスから関数を移動したときはOKでした。それはなぜ起こるのですか?クラスメンバーconstexpr関数を使用してメンバーconstexpr変数を初期化する方法はありますか?constexprメンバ関数を使用したconstexprメンバ変数の初期化

Apple LLVMバージョン8.0.0(clang-800.0.38)を使用しています。

ありがとうございました。

constexpr static int Add_Ext(int a, int b) { return a + b; } 


class Foo 
{ 
public: 
    constexpr static int Add_InClass(int a, int b) { return a + b; } 

    // This is OK. 
    constexpr static int kConstantX = Add_Ext(1, 2); 

    // This results in a compile error. 
    constexpr static int kConstantY = Add_InClass(1, 2); 

}; 

打ち鳴らすエラーメッセージ:

Constexpr variable 'kConstantY' must be initialized by a constant expression 
+0

http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1626 – Danh

答えて

0
CWG-1255から

CWG-1626

そのクラスが完了するまで、標準 constexprメンバ関数は定数式で使用することができないことを明確にする必要があります

あなたのコードは意図的に受け入れられないようです。しかし、この規格では、そのことをより明確にすべきである。

メンバーconstexpr変数を初期化するためにクラスメンバーconstexpr関数を使用する方法はありますか?

w.r.t.これらのDRは、いいえ、あなたは外部に、または代わりに別のクラスに移動できます。

+0

ああ、すべての権利。ありがとう! – Poinsettia

0

Danhに感謝します。あなたが話したWGスレッドを調べました。結局のところ、クラステンプレートにするとメンバーconstexpr関数を使用できることがわかりました。

// This works (it doesn't if you make it as a non-template class). 
template <typename T> 
class TemplateFoo 
{ 
public: 
    constexpr static T Add_InClass(T a, T b) { return a + b; } 
    constexpr static T kConstantY = Add_InClass(1, 2); 

}; 

// Even such a meaningless template works too. 
template <typename T> 
class TemplateBar 
{ 
public: 
    constexpr static int Add_InClass(int a, int b) { return a + b; } 
    constexpr static int kConstantY = Add_InClass(1, 2); 

}; 

// So, this would be a (dirty but) useful workaround 
// when you don't want to use the class as a template. 
// Any type could be used as the template argument, which has no meaning. 
using Bar = TemplateBar<char>; 
+0

そのDRが修正されたときに覚えています。テンプレートも許可されません – Danh

+0

本当に...この回避策は良くありません。 – Poinsettia

関連する問題