Let's say I have a type of lookup table which I can build for a given integer:
class FooLookupTable {
...
public:
FooLookupTable(int radix) {
...
}
};
Then there's a class whose template parameter is that same integer, and whose constructor initializes a member instance of this lookup table:
template <int radix> class Foo {
...
private:
FooLookupTable table;
public:
Foo () : FooLookupTable (radix) {
...
}
};
Throughout my code I instantiate these with various values of radix:
int main() {
...
Foo<1> myFoo;
Foo<1> yourFoo;
Foo<10> theirFoo;
...
}
This works and doesn't create any hairy threading or API issues. But it's not sharing the radix table for 1 between myFoo
and yourFoo
. I could hardcode a dependency on an assumed thread library, and build a global map that's filled on-demand. But my question is:
"In the modern C++11 world, is there a clean way designing a library for Foo which does not have dependencies outside of the standard libraries?"
I thought of using a static member for this, since each separate instantiation of a template class creates only one static member variable. But this brings up the question of who is responsible for declaring the space for the static member and whoever does so has to "know the right way to initialize it":
FooLookupTable Foo<1>::table (1);
FooLookupTable Foo<10>::table (10);
int main() {
...
Foo<1> myFoo;
Foo<1> yourFoo;
Foo<10> theirFoo;
...
}
Reading what's written on the subject like " C++ Static member initalization (template fun inside) " doesn't seem to turn up much hope...unless I'm missing something. Also, what would happen if Foo
instances themselves were static? :-/