tags:

views:

327

answers:

4

I have have the following code using templates and array dimension as template non-type parameter

template<int n> double f(double c[n]);
...
double c[5];
f<5>(c);  // compiles
f(c);  // does not compile

should not the compiler to be able to instantiate the second f without explicit template parameter? I am using g++4.1

thanks

+2  A: 

Unfortunately no, because when you pass double c[5] to f(), or any array to any function which takes an array for that matter, you lose the size information. You are only passing a pointer.

Edit: But see gf's answer for a workaround.

Charles Salvia
A: 

no, because in a different call, the argument might be coming from wherever. the compiler surely cannot chase your pointers at runtime.

edit: btw, this works for me, but requires -std=c++0x (I'm using gcc 4.4)

#include <iostream>

template <int n>
struct T
{
    T&
    operator=(double const cc[n])
    {
        c = cc;
        return *this;
    }
    const double
    operator[](int const &i)
    {
        return c[i];
    }
    double c[n];
};

template<int n>
double
f(T<n> & x)
{
    return x[n-1];
}

int
main()
{
    T<5> t5 = {10, 20, 30, 40, 50};
    T<3> t3 = {100, 200, 300};
    std::cout << f(t5) << std::endl;
    std::cout << f(t3) << std::endl;
    return 0;
}
just somebody
+8  A: 

It works when using references:

template<size_t n> double f(double (&c)[n]);
Georg Fritzsche
thanks this is exactly what I have been needing
aaa
A: 

This could help you with your larger problem (whatever that may be). This will allow you to query the size/type of the array at compilation.

template < typename T_, unsigned N_ >
class many {
public:
    typedef T_ T;
    enum { N = N_ };

    T array[N];
};

Justin

Justin