【问题标题】:Why is an external template redeclared as a "different kind of entity"?为什么将外部模板重新声明为“不同类型的实体”?
【发布时间】:2021-08-31 16:01:18
【问题描述】:

所以我试图在翻译单元之间共享一个模板化的全局变量。

对于函数执行此操作有一种通用策略,其中一个头文件声明/实现模板,第二个 C++ 文件显式枚举所有参数以实际生成链接器代码。

原版的样子

template<typename T>
struct PoolType
{
    void do_something()
    {

    }
};

template <class T>  PoolType<T> pool;

int main ()
{
    pool<int>.do_something(); 
    pool<float>.do_something();// can make other types 
}

将这种方法扩展到模板结构时,我遇到了一些奇怪的错误。有谁知道错误的含义以及“声明”了哪种实体?

template<typename T>
struct PoolType
{
    void do_something()
    {

    }
};

template <class T>  extern PoolType<int> pool; //Suppoedly can live in another TU
//In some other file
PoolType<int> pool;

// template <class T>  PoolType<int> pool; //works fine but limited to one TU
int main ()
{
    pool<int>.do_something(); 
}

海合会

 error: 'PoolType<int> pool' redeclared as different kind of entity

叮当

error: redefinition of 'pool' as different kind of symbol

godbolt

【问题讨论】:

    标签: c++ c++20 template-meta-programming linkage


    【解决方案1】:

    你可以做两件事之一。

    1. pool 设为普通变量。

      extern PoolType<int> pool;
      // in some other file
      PoolType<int> pool;
      // in main
      pool.do_something();
      
    2. pool 设为变量模板。

      template <class T> extern PoolType<T> pool;
      // in some other file
      template <> PoolType<int> pool<int>;
      // in main
      pool<int>.do_something();
      

    【讨论】:

    • 酷,template &lt;&gt; PoolType&lt;int&gt; pool&lt;int&gt;; 似乎是我需要的,但你能解释一下为什么需要两个&lt;int&gt; 标签吗?
    • 有一个名为pool&lt;int&gt;的对象,它的类型是PoolType&lt;int&gt;
    • 啊,我明白了,所以也许它需要多一层间接,以便对象被外部化:godbolt.org/z/bxnsxjfos
    • 您还需要在main 的翻译单元中声明您的显式特化(可能在与声明模板相同的标题中),尽管在实践中它通常有效反正。但是为什么不使用显式的实例化呢?
    • @DavisHerring 你的意思是class T 需要完整吗?
    猜你喜欢
    • 2021-10-13
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多