Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array of structs as template parameter

I am trying to pass a pointer to an array of structs as a template argument. I managed to do it after a while:

struct something{};

constexpr const something single;
constexpr const something array[12];
template<const something* arg> void f() {}

template<typename T>
constexpr T* workaround(T* v){
    return v;
};

void bind(){
    f<&single>();                       //OK
    f<array>();                         //NO
    f<&array>();                        //NO
    f<&array[0]>();                     //NO
    f<workaround(array)>();             //NO
    f<(const something*)array>();       //OK
}

Is this one of the rare cases where an array cannot be transparently used as a pointer, or is it a compiler bug?

like image 684
Lorenzo Pistone Avatar asked Jul 30 '26 02:07

Lorenzo Pistone


1 Answers

I actually believe the simplest form of the call, f<array>();, does work if only you declare-define array correctly:

struct Elem
{ };

constexpr const Elem array[5] { {} , {} , {} , {} , {} };

template<const Elem* arg> void f()
{ }

int main()
{
  f<array>();
  return 0;
}

The only thing I changed (apart from reducing the array from 12 to 5 elements) is to add an initializer for array.

(This compiles for me, using GCC 4.7.2.)

like image 180
jogojapan Avatar answered Aug 01 '26 17:08

jogojapan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!