Templates: howto return T or vector<T> from one template

M

Marco Nawijn

Hello,

I have a short question regarding the use of templates.
I have a template definition like the following:

template <typename T, uint64_t N=1>
T func(const stream &s)
{
// code..
}

Now, depending on whether N=1 or N>1 I would like to
return a variable of type T itself, or a vector<T>.
Is this possible with one template, or should I just
create a second template? If it is possible, how
should the return value of the function be specified?

Regards,

Marco
 
V

Victor Bazarov

I have a short question regarding the use of templates.
I have a template definition like the following:

template <typename T, uint64_t N=1>
T func(const stream &s)
{
// code..
}

Now, depending on whether N=1 or N>1 I would like to
return a variable of type T itself, or a vector<T>.
Is this possible with one template, or should I just
create a second template? If it is possible, how
should the return value of the function be specified?

It's better to wrap it into a class template, so you can actually
partially specialize it.

template<class T>
std::vector<T> func_N(const stream& s, uint64_t N) { ... }

teplate<class T>
T func_1(const stream& s) { ... } // case where N = 1

template<class T, uint64_t N>
struct func_helper {
typename std::vector<T> ret_t;
ret_t call(const stream& s) { return func_N(s, N); }
};

template<class T>
struct func_helper<T, 1> {
typename T ret_t;
ret_t call(const stream& s) { return func_1(s); }
};

So, in the call where you try to use your 'func' do this instead:

... = func_helper<myT, myN>::call(mystream);

Victor

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,525
Members
44,997
Latest member
mileyka

Latest Threads

Top