[英]Can I declare and use a static-non-template member of a template class in C++?
假設我有:
namespace name{
template< typename T >
class Example
{
....
};
}
我想要一個地圖實例,我將在所有繼承自Example
的類中使用它。 我想到的第一件事是擁有Example
的static
成員,但它會迫使我為每個將使用它的類擁有一個唯一的成員 - 由於內存使用限制,我不希望這樣(我在這里錯了嗎?)。
在namespace
中聲明它也會為每個編譯單元創建一個實例。
我該怎么做才能克服這個問題?
順便說一句,我最初的解決方案是 [使用 const extern map][1],但我無法理解我遇到的錯誤。
編輯:
我遵循了@SamVarshavchik 的回答,現在我遇到了與上一個問題相同的錯誤。
namespace name{
struct Example_base {
protected:
static std::map<std::string, int> the_same_map;
};
template< typename T >
class Example : public Example_base
{
....
};
}
結果
不能使用針對符號“name::Example_base::map”的偏移量 0xd3 處的 R_X86_64_PC32 重定位; 使用 -fPIC 重新編譯
對於每個編譯單元 [1] 中的每個用法: 使用 const extern 映射時的 R_X86_64_PC32 重定位
請注意,我有多個使用相同模板實現Example
的類的實例,並且我不能使用此標志
這就需要繼承。
namespace name{
struct Example_base {
protected:
static std::map<std::string, int> the_same_map;
};
template< typename T >
class Example : public Example_base
{
....
};
}
現在, Example
模板的任何實例的所有子類都共享the_same_map
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.