Reputation: 161
I would like to have a function that can take many different things (for simplicity) like so:
template <typename T>
typename type_to_return<T>::type // <-- Use type_to_return to get result type
foo(T t)
{
return typename type_to_return<T>::type(T); // <-- Build a thing!
}
I would then specialize the type_to_return
class for the types I have created. This would make the entry be one function and I could then just define new type_to_return
s and constructors.
I want type_to_return<T>::type
to be just T
if T
is not some class template. Otherwise I want it to be that class's first template parameter. So for int
, I get back int
, and for MultOp<float,int,double>
, I want to get back float
.
How do I do that? I think I need to do something like:
// Base version
template <typename T>
struct type_to_return
{
typedef T type;
};
// Specialized type
template <template <typename> class T>
struct type_to_return<T <any_type_somehow> >
{
typedef template boost::magic_type_unwrapper<T>::param<1>::type type;
};
Upvotes: 1
Views: 1281
Reputation: 217075
You may implement a type_unwrapper
as follow:
template <typename T>
struct type_unwrapper;
template <template <typename...> class C, typename... Ts>
struct type_unwrapper<C<Ts...>>
{
static constexpr std::size_t type_count = sizeof...(Ts);
template <std::size_t N>
using param_t = typename std::tuple_element<N, std::tuple<Ts...>>::type;
};
which works as long there is no template value as in std::array<T, N>
.
Note also that stl container declare some typedef
to retrieve there template arguments as std::vector<T, Alloc>::value_type
which is T
.
Upvotes: 4