Create static array with variadic templates

前端 未结 3 1500
孤街浪徒
孤街浪徒 2020-12-13 19:00

There was an answer on stackoverflow (which I can\'t seem to find anymore) which demonstrated how a variadic template can be used in C++11 to create a static array at compil

3条回答
  •  情深已故
    2020-12-13 19:49

    Non-type template arguments can also be pointers or references, provided they point or refer to an object with external linkage.

    template
    struct ref {
        static T&
        get() { return t; }
    };
    
    int i = 0;
    int& ri = ref::get(); // ok
    
    static int j = 0;
    int& rj = ref::get(); // not ok
    
    const int jj = 0; // here, const implies internal linkage; whoops
    const int& rjj = ref::get(); // not ok
    
    extern const int k = 0;
    const int& rk = ref::get(); // ok
    
    namespace {
    int l = 0;
    }
    int& rl = ref::get(); // ok, and l is specific to the TU
    

    I don't think you'd really want to init the elements with extern references though, since that would end up with twice the number of objects. You could initialize the elements of the array from literals, but unfortunately you can't use string literals as template arguments. So you'd need the proverbial layer of indirection: It's painful because arrays or array references can't appear in a template parameter list (I guess this is why string literals can't):

    // Not possible:
    // const char* lits[] = { "Hello, ", "World!" };
    // lit accepts const char*&, not const char*
    // typedef array_, lit, int_<42> > array;
    
    // instead, but painful:
    const char* hello = "Hello";
    const char* world = "World!";
    typedef array_, lit, int_<42> > array;
    /*
     * here array::data would be an array of T, size 3,
     * initialized from { hello, world, 42 }
     */
    

    I can't see how to avoid dynamic initialization without C++0x's constexpr, and even then there are limitations. Using some kind of tuple to build composite initializers (e.g. initialize from { { hello, world, 42 }, ... }) left as an exercise. But here's an example.

提交回复
热议问题