Anupam Srivastava
Anupam Srivastava

Reputation: 859

Template function over a templated typedef

I have class that takes two template arguments:

template< typename T, size_t Len >
struct A {
    size_t GetLen() const {
        return Len;
    }

    T mArr[Len];
};

typedef A< int, 10 > IntArrOfTenLen;
typedef A< int, 5 > IntArrOfTenFive;

So far so good. Now I want to write a function that can do something with such typedef'd variables. Something like this:

void f(_arr)
{
    std::cout << _arr[_arr.GetLen() - 1];
}

void g()
{
    IntArrOfTenLen arr;
    IntArrOfTenFive arr2;
    f(arr);
    f(arr2);
}

Is it possible? What should be the signature of such function f()?

I have tried following:

template< typename A >
void f(A _arr) {
    std::cout << _arr[_arr.GetLen() - 1];
}

This fails because Len is not provided, but that providing Len will be kind of defeating the purpose of writing GetLen(), isn't it?

Upvotes: 0

Views: 36

Answers (1)

TartanLlama
TartanLlama

Reputation: 65600

If you want f to take As of arbitrary type and length, make it a template function:

template <typename T, size_t Len>
void f(const A<T,Len>& arr) {
    //...
}

You don't need to supply T and Len with this template; they'll be deduced from the argument:

f(arr)  //f<int, 10>
f(arr2) //f<int, 5>

Of course, instead of reinventing the wheel, you could just use std::array in C++11 rather than writing your own.

Upvotes: 2

Related Questions