FailedDev
FailedDev

Reputation: 26920

Array element as non type template argument

is it possible to overcome this problem:

                class Constants
                { 
                    static Std_ReturnType dtcSitzheizungSchalteMittelkonsoleHlTasterHaengt( UInt8 const value )
                    {
                        return Rte_Call_demSitzheizungSchalteMittelkonsoleHlTasterHaengt_SetEventStatus( value );
                    }

                    static DTCSetter * const DTCSETTER_WITH_NO_DID[SEAT_HEATING_DTCS_COUNT]; //how to use an element of this array as a non type template parameter ?
                };

                template class ButtonStuckPolicy< &Constants::dtcSitzheizungSchalteMittelkonsoleHlTasterHaengt >; //works

in C++ 03?

In general, is it possible to pass a static array element as a non type template parameter ?

Thanks

Upvotes: 0

Views: 913

Answers (2)

j_kubik
j_kubik

Reputation: 6181

My solution - create template:

template <int* arr, int index>
class indexer{
public:
    static inline int* element(){ return arr+index; }
};

then you just say

template <int* arr, int index>
foo{
   // Here use indexer<arr,index>::element();
};

int x[10];
foo<x,0> f;

or perhaps even:

template <typename T>
bar{
   //here use T::element();
};

int x[10];
bar<indexer<x, 0> > b;

It's not as beautiful as foo<&x[0]>, and all your classes specialized on int* will have to change specialization, but you will probably not get it better (and working;)

Upvotes: 0

Potatoswatter
Potatoswatter

Reputation: 137770

The address of any object with external linkage is fair game in C++03. But the value is not, unless it is const and initialized with an integer constant expression. Subobjects, as you have, need not apply until C++11.

What you have is passing an address argument to an int parameter, which just won't work in any context.

This is OK in C++11:

const int x[100] = {}; // zero-initialize
template<int T>
class foo;
foo<x[0]> y;

So is this:

int x[100];
template<int *T>
class foo;
foo<&x[0]> y;

This is OK in C++03 as well because it uses the address of the whole, named object:

int x[100];
template<int *T>
class foo;
foo<x> y;

Upvotes: 1

Related Questions