Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   C++ (http://www.velocityreviews.com/forums/f39-c.html)
-   -   Templates: howto return T or vector<T> from one template (http://www.velocityreviews.com/forums/t957043-templates-howto-return-t-or-vector-t-from-one-template.html)

Marco Nawijn 01-29-2013 12:34 PM

Templates: howto return T or vector<T> from one template
 
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

Victor Bazarov 01-29-2013 02:38 PM

Re: Templates: howto return T or vector<T> from one template
 
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


All times are GMT. The time now is 08:28 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.