简体   繁体   中英

array of structs as template parameter

I am trying to pass a pointer to an array of struct s 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?

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.)

Fooling around with this with Apple clang v4.1, I've arrived at the below code which compiles. I have to admit I don't know if it's correct of Clang to insist on external linkage for single and array . Also, based it on jogojapan's modifications for no particular reason.

struct Elem {};

extern const Elem single;
extern const Elem array[3];

constexpr const Elem single {};
constexpr const Elem array[3] {{},{},{}};

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

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

FWIW, I arrived at this shot in the dark after stumbling across this: http://lists.apple.com/archives/xcode-users/2006/Jun/msg00799.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM