Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Templates: howto return T or vector<T> from one template

Reply
Thread Tools

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

 
 
Marco Nawijn
Guest
Posts: n/a
 
      01-29-2013
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
 
Reply With Quote
 
 
 
 
Victor Bazarov
Guest
Posts: n/a
 
      01-29-2013
On 1/29/2013 7:34 AM, Marco Nawijn wrote:
> 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
--
I do not respond to top-posted replies, please don't ask
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
If number is 0 return zero else return one Lakshmi Sreekanth C Programming 11 09-16-2009 08:02 AM
If number < 0 return zero else return one Lakshmi Sreekanth C Programming 17 09-16-2009 07:27 AM
If number < 0 return zero else return one Lakshmi Sreekanth C Programming 0 09-14-2009 01:03 PM
what value does lack of return or empty "return;" return Greenhorn C Programming 15 03-06-2005 08:19 PM
Can a template function return a template type? Damon C++ 2 12-15-2003 12:56 PM



Advertisments