0

I have a template class that looks something like this:

template <typename T>
class foo
{
    static const T arr[16];
};

The contents of foo<T>::arr are numerically identical for all types T that I plan to use. For example, I would initialize it for T = float and T = double by placing lines in a source file as follows:

float foo<float>::arr[16] = {1, 2, 3, 4, ...};
double foo<double>::arr[16] = {1, 2, 3, 4, ...};

Is there a way that I can initialize this in one place without having to repeat myself and enumerate all of the types that T can take on? Note that since the type of each array element is T, I can't use the trick of deriving foo<T> from a non-template base class that holds the static array.

Jason R
  • 11,159
  • 6
  • 50
  • 81

1 Answers1

2

What have you tried? This works for me:

#include <iostream>
using namespace std;

template<typename T>
struct Foo {
    static T const arr[16];
};

template<typename T>
T const Foo<T>::arr[16] = {1,2,3,4};

int main() {
    for ( float const *f = Foo<float>::arr; f != Foo<float>::arr+16; ++f ) {
        cout << *f << " ";
    }
    cout << endl;
    for ( double const *d = Foo<double>::arr; d != Foo<double>::arr+16; ++d ) {
        cout << *d << " ";
    }
    cout << endl;
}
Adam H. Peterson
  • 4,511
  • 20
  • 28
  • I'm trying to avoid the problem of multiple instantiations of the static variable that can occur when you initialize it in a header file ([described here, for instance](http://stackoverflow.com/questions/185844/initializing-private-static-members)). I think that this method would trigger that problem if the declaration of `foo` was in a header that was included by multiple compilation units. – Jason R Feb 11 '14 at 16:51
  • Why not `for(auto d = std::begin(Foo::arr); d != std::end(Foo::arr); ++d )`.... or why not `for(auto const & i : Foo::arr)` – Nawaz Feb 11 '14 at 16:51
  • @Nawaz, I'm sticking with C++03, since the question was'nt tagged as C++11. If I were working in C++11, I would have written it that way. – Adam H. Peterson Feb 11 '14 at 16:52
  • 1
    @JasonR: The rules are different for templates. The multiple generated definitions in separate translation units should be coalesced into single definitions by the linker. If a compiler/linker emitted an error for this with a template, that would be nonconforming. – Adam H. Peterson Feb 11 '14 at 16:55