简体   繁体   English

模板类中的静态成员

[英]Static member in a template class

I have a templated class and a static member of it, which is of type map. 我有一个模板化的类和它的静态成员,它是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() : 我在函数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;
}

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

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: 或者以下C ++ 11语法:

template <>
si_map_t A<string>::my_map_ = {};

or 要么

template <>
si_map_t A<string>::my_map_{};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM