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

我将特化代码放在.cpp文件中,以避免在同一.cpp末尾出现类似“已经声明”(???)的错误,一旦该类的所有知识都知道了,便宣布该特化代码存在。这是代码:

Class.h

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

Class.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将不再是必需的,除非它具有上面几行以外的代码。

10-07 19:31
查看更多