Reputation: 1134
I want to write a class which has a parameter pack and a function. This function should return the value itself, if there is only one type in the pack and otherwise it should return a tuple. If there pack is empty it can return an empty tuple or void, I don't mind.
Something like this(pseudocode):
template<typename ...Args>
class A{
std::tuple<Args...> data;
#if sizeof...(Args)
std::tuple<Args...> get();
#else
Args[0] get();
#endif
};
I think my current solution is very complicated and it doesn't work if Args is empty.
Current solution:
template<bool EnableBool = true>
typename std::enable_if<
EnableBool && std::tuple_size_v<decltype(data)> == 1, typename std::tuple_element<0, decltype(data)>::type>::type
get();
Upvotes: 2
Views: 145
Reputation: 20936
Since C++17 you can use if constexpr
and return type will be deduced by compiler:
template<typename ...Args>
class A{
std::tuple<Args...> data;
public:
auto get()
{
if constexpr (sizeof...(Args) > 1)
return data;
else if constexpr (sizeof...(Args) == 1)
return std::get<0>(data);
else
return;
}
};
int main (int argc, char *argv[])
{
A<int,double> a;
static_assert(std::is_same_v<decltype(a.get()),std::tuple<int,double>>);
A<> b;
static_assert(std::is_same_v<decltype(b.get()),void>);
A<int> c;
static_assert(std::is_same_v<decltype(c.get()),int>);
Upvotes: 4