Different base class depending on template parameters

Viewed 210

Is it possible to determine at compile-time the exact base of a class template depending on its parameters? E.g. I have a class template, that accepts one argument in its constructor, and I want to extend this class with another argument, for which another constructor will be used. The problem is that this second instantiation (with two arguments) must have different base class than the one with one parameter. I can detect the proper base class with std::conditional, but the issue is in having both constructors in one class template. E.g.:

#include <type_traits>

struct X
{
};

struct Y
{
};

struct XX
{
};

struct XY
{
};


template<class T, class V = void>
struct Z: public std::conditional_t<std::is_void_v<V>, XX, XY>
{
    Z(T&& t, V&& v)
        : XY()
    {
        // do smth with t and v
    }

    Z(T&& t)
        : XX()
    {
        // do smth with t
    }
};

int main()
{
    auto a = Z(X(), Y());
    auto b = Z(X());         // <-- this instantiation fails
}

Here Z(X(), Y()) works, but for Z(X()) it fails with compile error:

main.cpp: In instantiation of 'struct Z<X, void>':

main.cpp:39:19:   required from here

main.cpp:23:5: error: forming reference to void

   23 |     Z(T&& t, V&& v)

      |     ^

Update:

Tried to make the two-args ctor a template with enable_if, but it does not work (same forming reference to void as in the original code):

    template<class = std::enable_if<! std::is_void_v<V>>>
    Z(T&& t, V&& v)
        : XY()
    {
        // do smth with t and v
    }
2 Answers

Not an elegant solution, but seems can work, use partial specialization and deduction guide.

template<class T, class V>
struct Z: public XY
{
    Z(T&& t, V&& v)
        : XY()
    {
        // do smth with t and v
    }
};

template<class T>
struct Z<T, void> : public XX
{
    Z(T&& t)
    : XX()
    {

    }
};

template <class T>
Z(T&& ) -> Z<T, void>;

The usual approach for advanced conditional class definition is a dependent base class:

struct B1 {};
struct B2 {};

template<class T>
struct Z1 : B1 {
  Z1(T&&) : B1() {}
};
template<class T,class V>
struct Z2 : B2 {
  Z2(T&&,V&&) : B2() {}
};

template<class T,class V>
using Z0=std::conditional_t<std::is_void_v<V>,Z1<T>,Z2<T,V>>;

template<class T,class V=void>
struct Z : Z0<T,V> {
  using Z0<T,V>::Z0;
};
template<class T> Z(T) -> Z<T>;
template<class T,class V> Z(T,V) -> Z<T,V>;

The deduction guides are needed because only the primary template (without its inherited constructors) is considered for CTAD.

If the Z that results from this transformation has no members of its own, C++20 may offer an opportunity to use (what is here called) Z0 directly, since it supports CTAD for alias templates.

Related