frozenca
frozenca

Reputation: 877

Conditionally enable member function of base class

I have some classes similar to:

class A {
    void func();
};

class B1 : public A {
    using A::func;
};

class B2 : public A {
    void func();
};

Because class B1 and B2 in my project share most things, I want to make them as a common class that is distinguished by a template parameter:

class A {
    void func();
};

template <bool Use = false>
class B : public A {
    using A::func; // how can I activate this only if Use is true
};

How can I activate using A::func; only if Use is true?

Upvotes: 1

Views: 63

Answers (2)

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38773

Try specializations.

template <bool Use = false>
class B : public A {
};

template <>
class B<true> : public A {
    using A::func; // activate this only if Use is true
};

Upvotes: 4

Daniel
Daniel

Reputation: 31579

You can use a specialization:

template<bool Use>
class B : public A {};

template<>
class B<false> {};

If the rest of the class is common, you can join them:

template<bool Use>
class C : public B<Use>
{
    int i;
};

Upvotes: 4

Related Questions