简体   繁体   English

我可以在 C++ 中声明和使用模板类的静态非模板成员吗?

[英]Can I declare and use a static-non-template member of a template class in C++?

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 .我想要一个地图实例,我将在所有继承自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?).我想到的第一件事是拥有Examplestatic成员,但它会迫使我为每个将使用它的类拥有一个唯一的成员 - 由于内存使用限制,我不希望这样(我在这里错了吗?)。

Declaring it in the namespace will also create an instance for each compilation unit.namespace中声明它也会为每个编译单元创建一个实例。

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.顺便说一句,我最初的解决方案是 [使用 const extern map][1],但我无法理解我遇到的错误。

EDIT:编辑:

I've followed @SamVarshavchik answer, and now I'm getting the same error as in the previous question.我遵循了@SamVarshavchik 的回答,现在我遇到了与上一个问题相同的错误。

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;不能使用针对符号“name::Example_base::map”的偏移量 0xd3 处的 R_X86_64_PC32 重定位; recompile with -fPIC使用 -fPIC 重新编译

For each usage in every compilation unit [1]: R_X86_64_PC32 relocation when using a const extern map对于每个编译单元 [1] 中的每个用法: 使用 const extern 映射时的 R_X86_64_PC32 重定位

Note that I've multiple instances of the classes that implement Example with the same template and that I can't use this flag请注意,我有多个使用相同模板实现Example的类的实例,并且我不能使用此标志

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 .现在, Example模板的任何实例的所有子类都共享the_same_map

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

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