0

Basically I would like to have a static array of pointers to template classes. A sort of map from or lookup table where to an index corresponds a template class. II'll try to explain my question better with the code example below.

#include <iostream>

struct TemplateInterface
{
    virtual int get()  = 0;
};

template<int I>
struct TemplatedStruct : public TemplateInterface
{
    int get() override { return I; }
};

// --------------------------------------------------------------------------
// Refactor this section with metaprogramming so to have classes from 1 to N
// --------------------------------------------------------------------------
static TemplatedStruct<1> one;
static TemplatedStruct<2> two;
static TemplatedStruct<3> three;


static TemplateInterface* TIArray[3] = {&one, &two, &three};
// --------------------------------------------------------------------------


int main() {
    for(int i = 0; i < 3; ++i)
    {
        TemplateInterface* ptr = TIArray[i];
        std::cout << ptr->get() << std::endl;
    }
}
3
  • template base class collection - C++ Senioreas Commented Dec 31, 2020 at 11:52
  • Are you sure you want them to be const? You are flirting with UB with that const_cast Commented Dec 31, 2020 at 14:31
  • @Jarod42 and [at]AndyG thanks, my mistake. I have updated the question to be more simple and clear. Commented Dec 31, 2020 at 14:36

1 Answer 1

3

You might have

template <std::size_t... Is>
std::array<TemplateInterface*, sizeof...(Is)>
makeInterfaceArray(std::index_sequence<Is...>)
{
    static std::tuple<TemplatedStruct<Is>...> data{};
    return {{ &std::get<Is>(data)... }};
}

template <std::size_t N>
std::array<TemplateInterface*, N> makeInterfaceArray()
{
    return makeInterfaceArray(std::make_index_sequence<N>{});
}


int main() {
    for (TemplateInterface* ptr : makeInterfaceArray<3>())
    {
        std::cout << ptr->get() << std::endl;
    }
}

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Seems very clean, but I am not able to compile your code here godbolt.org/z/z618fs ... do I miss something?
@giuseppe: Typo fixed, and Demo added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.