let's say I have:
namespace name{
template< typename T >
class Example
{
....
};
}
I want to have a single instance of a map that I'll use across all the classes that inherit from Example
. The first thing that came into my mind was having a static
member of Example
but it will force me to have a unique member for each class that will use it - and I don't want that due to memory usage restrictions (Am I wrong here?).
Declaring it in the namespace
will also create an instance for each compilation unit.
What can I do to overcome this?
BTW my initial solution was to [use a const extern map][1] but I can't understand the error I'm getting there.
EDIT:
I've followed @SamVarshavchik answer, and now I'm getting the same error as in the previous question.
namespace name{
struct Example_base {
protected:
static std::map<std::string, int> the_same_map;
};
template< typename T >
class Example : public Example_base
{
....
};
}
Results
R_X86_64_PC32 relocation at offset 0xd3 against symbol `name::Example_base::map' can not be used; recompile with -fPIC
For each usage in every compilation unit [1]: R_X86_64_PC32 relocation when using a const extern map
Note that I've multiple instances of the classes that implement Example
with the same template and that I can't use this flag
CodePudding user response:
This calls for inheritance.
namespace name{
struct Example_base {
protected:
static std::map<std::string, int> the_same_map;
};
template< typename T >
class Example : public Example_base
{
....
};
}
Now, all subclasses of any instance of the Example
template share the_same_map
.