Reputation: 2595
I have the following functions:
//method takes 2 or more template parameters
template <class A1, class A2, class ...Ax>
Value<FooMany> getValue() {
//note, FooAll's ctor takes std::string and std::initializer_list<std::size_t>
FooAll<Item> hairyStructure("abc", { Foo<A1>::getIndex(), Foo<A2>::getIndex(), Foo<Ax>::getIndex() ... } );
return Value<FooMany>(someData, hairyStructure);
}
//method takes only 1 template parameter
template <class A>
Value<FooSingle> getValue() {
//note, FooOne's ctor takes std::string and std::size_t
FooOne<Item> hairyStructure("abc", Foo<A>::getIndex() );
return Value<FooSingle>(someData, hairyStructure);
}
.
Obviously, the types of these functions are different.
I wonder, is it possible to squash these two into the single method, which, utilizing the C++11 features (decltype, I suppose), would auto-deduce the return type?
So, basically, it should return Value<FooSingle>
if getValue
is invoked as
GetValue<A>();
and it should return Value<FooMany>
if it is invoked for example as
GetValue<A, B>();
or
GetValue<A, B, C>();
I am not sure if my terminology is correct regarding "method takes 2 or more template parameters". Please correct me if it is wrong.
If it helps, my question continues the previous topic: C++11 parameters pack overload
Thank you.
Upvotes: 2
Views: 196
Reputation: 48447
#include <type_traits>
template <class A1, class... Ax>
auto getValue()
-> Value<typename std::conditional<sizeof...(Ax) == 0
, FooSingle, FooMany>::type>
{
typename std::conditional<sizeof...(Ax) == 0
, FooOne<Item>
, FooAll<Item>>::type
hairyStructure("abc", { Foo<A1>::getIndex(), Foo<Ax>::getIndex()... } );
return Value<typename std::conditional<sizeof...(Ax) == 0
, FooSingle, FooMany>::type>(hairyStructure);
}
Upvotes: 1