Mircea Ispas
Mircea Ispas

Reputation: 20790

Declaring member or not depending on template parameter

Is it possible to declare or not a member variable depending on template condition without using dummy empty type?

Example:

struct empty{};
struct real_type{};

template<bool condition>
struct foo
{
    typename std::conditional<condition, real_type, empty>::type _member;
};

Upvotes: 17

Views: 2547

Answers (2)

jww
jww

Reputation: 102336

Is it possible to declare or not a member variable depending on template condition without using dummy empty type?

I believe you can also specialize without the derivation. This tested OK under both -std=c++03 and -std=c++11.

template<bool condition>
struct foo;

template<>
struct foo<true>
{
    real_type _member;
};

template<>
struct foo<false>
{
};

It sure would have been nice if the C++ committee gave us what we wanted/needed:

template<bool condition>
struct foo
{
#if (condition == true)
    real_type _member;
#endif
};

Upvotes: 1

Andy Prowl
Andy Prowl

Reputation: 126492

You can derive from a template that has a specialization:

struct real_type { };

template<bool c>
struct foo_base { };

template<>
struct foo_base<true>
{
    real_type _member;
};

template<bool condition>
struct foo : foo_base<condition>
{
};

As a small test:

int main()
{
    foo<true> t;
    t._member.x = 42; // OK

    foo<false> f;
    f._member.x = 42; // ERROR! No _member exists
}

Upvotes: 16

Related Questions