这有点过时了,但我想我会把它留在这里以防它帮助其他人。我在谷歌上搜索导致我来到这里的模板专业化,虽然 @maxim1000 的回答是正确的,并最终帮助我解决了我的问题,但我认为它并不十分清楚。
我的情况与 OP 的情况有些不同(但我认为足以留下这个答案)。基本上,我使用的是第三方库,其中包含定义“状态类型”的所有不同类型的类。这些类型的核心只是enums,但这些类都继承自一个公共(抽象)父类并提供不同的实用函数,例如运算符重载和static toString(enum type) 函数。每个状态enum 彼此不同且不相关。例如,一个enum 有NORMAL, DEGRADED, INOPERABLE 字段,另一个有AVAILBLE, PENDING, MISSING 等。我的软件负责管理不同组件的不同类型的状态。我想为这些enum 类使用toString 函数,但由于它们是抽象的,我无法直接实例化它们。我可以扩展我想使用的每个类,但最终我决定创建一个template 类,其中typename 将是我关心的任何具体状态enum。关于这个决定可能会有一些争论,但我觉得这比用我自己的自定义类扩展每个抽象 enum 类并实现抽象函数要少得多。当然,在我的代码中,我只想能够调用.toString(enum type) 并让它打印出enum 的字符串表示形式。由于所有enums 都完全不相关,因此它们每个都有自己的toString 函数(经过一些研究我了解到)必须使用模板特化来调用。这把我带到了这里。下面是我必须做的一个 MCVE,以使其正常工作。实际上我的解决方案与@maxim1000 的有点不同。
这是enums 的(大大简化的)头文件。实际上,每个enum 类都在它自己的文件中定义。此文件表示作为我正在使用的库的一部分提供给我的头文件:
// file enums.h
#include <string>
class Enum1
{
public:
enum EnumerationItem
{
BEARS1,
BEARS2,
BEARS3
};
static std::string toString(EnumerationItem e)
{
// code for converting e to its string representation,
// omitted for brevity
}
};
class Enum2
{
public:
enum EnumerationItem
{
TIGERS1,
TIGERS2,
TIGERS3
};
static std::string toString(EnumerationItem e)
{
// code for converting e to its string representation,
// omitted for brevity
}
};
添加这一行只是为了将下一个文件分成不同的代码块:
// file TemplateExample.h
#include <string>
template <typename T>
class TemplateExample
{
public:
TemplateExample(T t);
virtual ~TemplateExample();
// this is the function I was most concerned about. Unlike @maxim1000's
// answer where (s)he declared it outside the class with full template
// parameters, I was able to keep mine declared in the class just like
// this
std::string toString();
private:
T type_;
};
template <typename T>
TemplateExample<T>::TemplateExample(T t)
: type_(t)
{
}
template <typename T>
TemplateExample<T>::~TemplateExample()
{
}
下一个文件
// file TemplateExample.cpp
#include <string>
#include "enums.h"
#include "TemplateExample.h"
// for each enum type, I specify a different toString method, and the
// correct one gets called when I call it on that type.
template <>
std::string TemplateExample<Enum1::EnumerationItem>::toString()
{
return Enum1::toString(type_);
}
template <>
std::string TemplateExample<Enum2::EnumerationItem>::toString()
{
return Enum2::toString(type_);
}
下一个文件
// and finally, main.cpp
#include <iostream>
#include "TemplateExample.h"
#include "enums.h"
int main()
{
TemplateExample<Enum1::EnumerationItem> t1(Enum1::EnumerationItem::BEARS1);
TemplateExample<Enum2::EnumerationItem> t2(Enum2::EnumerationItem::TIGERS3);
std::cout << t1.toString() << std::endl;
std::cout << t2.toString() << std::endl;
return 0;
}
这个输出:
BEARS1
TIGERS3
不知道这是否是解决我的问题的理想解决方案,但它对我有用。现在,无论我最终使用了多少枚举类型,我所要做的就是在 .cpp 文件中为 toString 方法添加几行,我可以使用库已经定义的 toString 方法而无需实现它自己而不是扩展我想使用的每个 enum 类。