2017-11-25 14 views
0

다음을 작성하는 데 "깨끗한"방법 (중복 코드가 없음)이 없습니까?"Enable_if"struct data menber

template < bool condition > 
class Test { 

    struct Foo1 { 

    int a; 
    }; 

    struct Foo2 { 

    int a; 
    int b; 
    }; 

    using type = std::conditional_t<condition, Foo1, Foo2>; 
}; 

내가 여기에서하고 싶은 것은 구조체의 단일 데이터 멤버를 활성화 또는 비활성화하는 것입니다. 그래서 하나의 구조체 만 필요하면 멋질 것입니다.

뭔가 같은 :

template < bool condition > 
class Test { 

    struct type { 
    int a; 
    if constexpr(condition) 
     int b; 
    }; 
}; 
+2

상속은 어떨까요? 'Foo2'를'Foo1'에서 상속 받습니까? 그것은 적어도 "중복 코드가 적다"는 것을 의미합니다. 이것은 또한 객체 지향 언어로 구조와 클래스를 확장하는 "자연스러운"방법입니다. –

+0

@Someprogrammerdude 그렇습니다. 코드가 적을 것이지만 그것이 제가 원하는 바가 아닙니다. 나는 더 많은 문맥을 추가 할 필요가 있다고 생각한다. –

+0

@MathieuVanNevel : 당신이 왜 * 왜 * 당신이 원하는지 설명하지 않았기 때문에 그것은 "더 많은 맥락"이 아닙니다. 어떻게 사용할 계획입니까? –

답변

1

이 당신을 위해 "청소기"인 경우 나도 몰라,하지만 ... 당신이 이런 식으로 자동 상속 (일종의) 클래스 Foo을 쓸 수 있습니다 (

// common part 
template <bool> 
struct Foo 
{ int a; }; 

// only when `Cond` is true 
template <> 
struct Foo<true> : public Foo<false> 
{ int b; }; 

Test

template <bool Cond> 
struct Test 
{ using type = Foo<Cond>; }; 
될) 불행하게도, 할 수있어하지만 외부 Test

다음은 전체 컴파일 예제입니다.

template <bool> 
struct Foo 
{ int a; }; 

template <> 
struct Foo<true> : public Foo<false> 
{ int b; }; 

template <bool Cond> 
struct Test 
{ using type = Foo<Cond>; }; 

int main() 
{ 
    decltype(Test<true>::type::a) a1; 
    decltype(Test<true>::type::b) b1; 
    decltype(Test<false>::type::a) a0; 
    // decltype(Test<false>::type::b) b0; // compilation error 
} 
+0

노력해 주셔서 감사합니다.하지만 필자가 작성한 의사 코드와는 여전히 멀리 떨어져 있습니다. 어쨌든 가능하지는 않겠지 만 조금만 기다려 둡니다. –

+0

@MathieuVanNevel - 불행히도 단순히 데이터 멤버가 아닌 메서드를 활성화/비활성화하는 방법을 알고 있습니다. – max66