Denis
Denis

Reputation: 1534

define different instantiation of a templated static class member

I want to wrap some stuff in a simple templated class:

template <int dim>
class internal {
    static unsigned int table[dim][dim];
};

And fill the table for different templated parameters:

template <>
unsigned int
internal<1>::table[1][1]  = {{0}};

template<>
unsigned int
internal<2>::table[2][2] =
                {{0, 1},
                 {2, 3}
                };

But I run into a duplicate symbols problem:

12 duplicate symbols for architecture x86_64

Something is wrong, but what? p/s/ a quick search over topic does not relieve similar questions.

Upvotes: 1

Views: 85

Answers (1)

Arne Mertz
Arne Mertz

Reputation: 24606

The definitions need to be in a .cpp file. Since you surely won't give those definitions for tons of dimensions, you'll want to get compiler errors if a wrong dimension is picked. Your implementation could look like this then:

Header:

template <int dim>
class internal {
    static unsigned int table[dim][dim];
    static_assert(dim <= 3, "Dimension too big!");
};

Source:

template <>
unsigned int
internal<1>::table[1][1]  = {{0}};

template<>
unsigned int
internal<2>::table[2][2] =
                {{0, 1},
                 {2, 3}
                };

template<>
unsigned int
internal<3>::table[3][3] =
                {{0, 1, 2},
                 {3, 4, 5},
                 {6, 7, 8}
                };

Note: Unlike normals static template member variables, you need not and must not define the table in the header, because you have no templated versions of it but all full specializations.

Upvotes: 1

Related Questions