gpt4 book ai didi

c++ - 不能强制实例化专用模板

转载 作者:行者123 更新时间:2023-11-30 03:45:32 25 4
gpt4 key购买 nike

静态库中,我在 Class.h 中声明了一个模板,然后在 Class.cpp 中专门化了一些方法。我想在链接到该库的项目中使用此类。

我将特化放在 .cpp 文件中,以避免在同一个 .cpp 的末尾出现诸如“已声明”(???) 之类的错误,一旦该类的所有内容都已知,我就声明了特化的存在。这是代码:

类.h

#ifndef __CLASS_H__
#define __CLASS_H__
template<class T>
class Class
{
public:
~Class(){}
Class(){}
//...
void method1()
{ /* unspecialized job here */ }
};
#endif

类.cpp

#include "Class.h"

template<>
void Class<bool>::method1()
{
/* Specialized job for bool here */
}

// Declare that the class is specialized for bool
template class Class<bool>;

现在,在我使用该库的项目中,当我尝试实例化 class Class<bool> 的对象时, 它仍然使用未专门化 方法。

问题是什么?在 .cpp 文件末尾使用"template"是否正确?

如果它很重要,我会在 Kubuntu/Raspbian 上使用 gcc 4.8/4.9,我会使用 C++11。

最佳答案

模板特化

template<>
void Class<bool>::method1()
{
/* Specialized job for bool here */
}

// Declare that the class is specialized for bool
template class Class<bool>;

仅在 Class.cpp 中可见。如果Class<bool>在您的代码中的其他任何地方使用,这些专业在那里是不可见的。因此,通用类模板用于实例化 Class<bool> .

如果您希望特化对Class<bool> 所在的所有文件可见被使用,将它们移动到 Class.h。届时,Class.cpp 将不再是必需的,除非它具有除上述行以外的代码。

关于c++ - 不能强制实例化专用模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34736077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com