lundi 4 décembre 2017

Building a constexpr template struct (C++11)

I have this code, which works... so far so good :

struct _TYPEIDSTR {};
typedef _TYPEIDSTR *TYPE_ID;
template<class T> _TYPEIDSTR _TYPE_ID;

template<class T> constexpr TYPE_ID getTypeID() { return &_TYPE_ID<T>; }

calling in main like this :

constexpr TYPE_ID id1 = getTypeID<int>();
constexpr TYPE_ID id2 = getTypeID<int>();
RLOG("ID1 : " << id1);
RLOG("ID2 : " << id2);

works perfectly, and I've an unique identifier for each type used in getTypeID() call. Now I want to build a struct that brings some info about a function :

template<typename RES, typename... ARGS> struct _GlobalOverlayInfo {
    bool _member;
    RES(*_fn)(ARGS...);
    size_t _nargs;
    TYPE_ID _argIDs;
    constexpr _GlobalOverlayInfo(RES(*fn)(ARGS...)) :
    _member(false),
    _fn(fn),
    _nargs(sizeof...(ARGS)),
    _argIDs {getTypeID<ARGS>()...}
    {}
};

template<typename RES, typename... ARGS>
constexpr auto getOverlayInfo(RES(*fn)(ARGS...)) {
    return & _GlobalOverlayInfo<RES, ARGS...>(fn); <<---ERROR1
}

using this function :

int pippo(int x) {
    return 0;
}

and calling like this :

constexpr auto x = getOverlayInfo(pippo); <<--- ERROR2

I get the 2 marked errors; ERROR1 is "taking address of a temporary" (but shouldn't it a compile time evaluation ?) and ERROR2 is "error: ‘&’ is not a constant expression". I tried in many ways, but I couldn't success. Where I am wrong ? Is there a way (in C++11) to achieve this result ? All I need is a pointer to an unique structure generated for each RES and ARGS... parameters.

Aucun commentaire:

Enregistrer un commentaire