2016-12-17 1 views
4

constexpr 멤버 함수를 사용하여 constexpr 멤버 변수를 초기화하려고했지만 컴파일하지 않았습니다. 내가 클래스에서 함수를 옮기면 괜찮 았어. 왜 그렇게됩니까? 멤버 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

관련 문제