Search code examples
c++templatesexternforward-declaration

How to declare an extern array of template class objects with a forward declared template class in C++?


Consider the following existing code (which compiles and executes as expected):

/* File foo.h */

extern const struct Foo bar[]; /* Definition in foo.cpp */

struct Foo
{
    Foo(int i) : Foo(bar[i]) {}
    int x;
};

I now want to change Foo to a template class, such that:

template <typename T>
struct Foo
{
    Foo(int i) : Foo(bar[i]) {}
    T x;
};

How do I need to declare extern const struct Foo bar[] now so that the code will compile?


Solution

    • First, forward declare template <typename T> struct Foo.
    • Then, declare bar using the forward declared Foo.

    template <typename T>
    struct Foo;
    
    extern const Foo<int> bar[];
    
    template <typename T>
    struct Foo
    {
        Foo(int i) : Foo(bar[i]) {}
        T x;
    };