jeudi 26 octobre 2017

Initializing a const vector of pointers to array at compile time using templates

The following class will not compile under C++11; the loop as it stands can only be executed at runtime and so one gets a "char(*)[i] is a variably-modified type" error from the template class static function call within the loop:

#include <cstddef>
#include <vector>

template <std::size_t N>
class Foo
{
private:
    const std::vector<char(*)[]> bar = bar_init();

    static std::vector<char(*)[]> bar_init()
    {
        std::vector<char(*)[]> init;

        for (size_t i = N; i > 0; i >>= 1)
        {
            auto ptr_to_array = MyClass<char(*)[i]>::static_return_ptr_to_array();
            init.emplace_back(reinterpret_cast<char(*)[]>(ptr_to_array));
        }

        return init;
    }
};

Is there a way in I can accomplish the same effect using templates within the initialization function? That is to say, initialize "bar" of size log2(N) at "Foo" class instantiation as a const vector of pointers to array of char with each vector element containing e.g. for N=32 the output of:

MyClass<char(*)[32]>::static_return_ptr_to_array();
MyClass<char(*)[16]>::static_return_ptr_to_array();
MyClass<char(*)[8]>::static_return_ptr_to_array();

//etc...

Aucun commentaire:

Enregistrer un commentaire