Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic template constructor and empty constructor?

I have a class like the following:

template<typename ... TTypes>
class Composite {
public:
    //Composite() : null(true) { } 
    Composite(TTypes... values) : values(std::make_tuple(values...)), null(false) { }
private:
    bool null;
    std::tuple<TTypes...> values;
};

int main(int argc, char *argv[]) {
    Composite<int, char, int> a1;
}

But this leads to an error because the second constructor would override the first one with TTypes = {}. Is there any way to keep the empty constructor?

Best, Moritz

like image 351
moo Avatar asked Oct 24 '25 09:10

moo


1 Answers

Since none of the existing answers so actually solve the problem, but there is a solution by Piotr Skotnicki hidden in the comments, I'm just gonna repost it here for visibility:

#include <tuple>
#include <type_traits>

template<typename ... TTypes>
class Composite {
public:
    Composite() : null(true) { } 

    template <std::size_t N = sizeof...(TTypes), typename std::enable_if<(N>0), int>::type = 0>
    Composite(TTypes... values) : values(std::make_tuple(values...)), null(false) { }
private:
    bool null;
    std::tuple<TTypes...> values;
};

int main(int argc, char *argv[]) {
    Composite<int, char, int> a1;
    Composite<> a2;
}
like image 172
SteakOverflow Avatar answered Oct 26 '25 22:10

SteakOverflow