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

Discussion in 'C++' started by Marco Nawijn, Jan 29, 2013.

  1. Marco Nawijn

    Marco Nawijn Guest

    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
    Marco Nawijn, Jan 29, 2013
    #1
    1. Advertising

  2. 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
    Victor Bazarov, Jan 29, 2013
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. JKop
    Replies:
    3
    Views:
    468
  2. pmatos
    Replies:
    6
    Views:
    23,782
  3. Replies:
    8
    Views:
    1,914
    Csaba
    Feb 18, 2006
  4. recover
    Replies:
    2
    Views:
    799
    recover
    Jul 25, 2006
  5. Javier
    Replies:
    2
    Views:
    559
    James Kanze
    Sep 4, 2007
Loading...

Share This Page