Reputation: 3
I have a templated class and a static member of it, which is of type map.
I can't seem to figure out how to use that member. I have tried a few different variations but this is where it began.
I get an error in the definition of function size() :
undefined reference to `A<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >::my_map_'
#include <iostream>
#include <map>
#include <string>
using namespace std;
typedef map<string, int> si_map_t;
template<class T>
class A {
public:
static map<T, int> my_map_;
static void add(T key, int value) {
my_map_.insert(std::pair<T, int>(key, value));
}
static size_t size() {
return my_map_.size();
}
};
template<>
si_map_t A<string>::my_map_;
int main() {
A<string>::my_map_;
size_t count = A<string>::size();
cout << count << endl;
return 0;
}
Upvotes: 0
Views: 167
Reputation: 7473
If you really want to use explicit specialization of a class template member note that such notation
template <>
si_map_t A<string>::my_map_;
means only a declaration of a specialization. It is strange but it is true.
Use the following syntax to define a member specialization:
template <>
si_map_t A<string>::my_map_ = si_map_t();
Or the following C++11 syntax:
template <>
si_map_t A<string>::my_map_ = {};
or
template <>
si_map_t A<string>::my_map_{};
Upvotes: 1
Reputation: 66194
I think this is what you're trying to do:
template<typename T>
using si_map_t = std::map<T, int>;
template<class T>
class A {
public:
static si_map_t<T> my_map_;
static void add(T key, int value) {
my_map_.insert(std::pair<T, int>(key, value));
}
static size_t size() {
return my_map_.size();
}
};
template<typename T>
si_map_t<T> A<T>::my_map_;
int main()
{
size_t count = A<string>::size();
cout << count << endl;
return 0;
}
Output
0
Upvotes: 1