zaharpopov
zaharpopov

Reputation: 17292

Can I customize if class has member based on template argument?

Can I have a class that either has or not has member based on template? Imaginary code:

template <typename HasBazMember=true>
class Foo {
  int bar;

  ConditionallyHaveMember<int, HasBazMember> baz;
};

So in above I want Foo to have member "baz" and Foo not.

Upvotes: 2

Views: 84

Answers (2)

ipc
ipc

Reputation: 8143

Solution in C++11 without specialisazion:

class empty {};

template <typename T>
struct wrap { T wrapped_member; };

template <bool HasBazMember=true>
class Foo : private std::conditional<HasBazMember, wrap<int>, empty>::type {
public:
  int bar;

  int& baz() {
    static_assert(HasBazMember, "try using baz without HasBaz");
    return static_cast<wrap<int>&>(*this).wrapped_member;
  }
};


int main()
{
  Foo<true> t;
  t.baz() = 5;

  Foo<false> f;
  f.baz() = 5; // ERROR
}

Note that thanks EBO, there is no space overhead if HasBazMember=false.

Upvotes: 4

K-ballo
K-ballo

Reputation: 81409

Yes, you can, but you have to specialize the entire class. Example:

template< bool HasBazMember = true >
class Foo {
  int bar;
  int baz;
};

template<>
class Foo< false > {
  int bar;
};

If you can separate the logic, you can put those members in a base class so that you don't need to duplicate the code for the entire class. For instance,

template< bool HasBazMember >
class FooBase
{
protected:
   int baz;
};

template<>
class FooBase< false >
{
    // empty class
    // the Empty Base Optimization will make this take no space when used as a base class
};

template< bool HasBazMember = true >
class Foo : FooBase< HasBazMember >
{
    int bar;
};

Or using Boost.CompressedPair:

struct empty {};

template< bool HasBazMember = true >
class Foo
{
    boost::compressed_pair<
        int
      , typename std::conditional< HasBazMember, int, empty >::type
    > bar_and_maybe_baz_too;
};

Upvotes: 2

Related Questions