开发者

C++ template parameter in array dimension

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开发者_Go百科
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


It works when using references:

template<size_t n> double f(double (&c)[n]);


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.


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;
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜