Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different base class depending on template parameters

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
    }
like image 821
Student4K Avatar asked Dec 06 '25 19:12

Student4K


1 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>;
like image 168
user8510613 Avatar answered Dec 08 '25 10:12

user8510613



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!