我有一个类,它允许创建一个包含任何类型或类的 vector 。不过,我想为数字类型添加额外的功能。
template <>
class Vec<double> : public VecBase<double>
{
// == METHODS ==
public:
// -- Constructors & Destructors --
explicit Vec(const unsigned long long t_size);
virtual ~Vec();
// -- Operators --
friend Vec<double> operator+(const Vec<double>&, const double);
// -- Methods --
double sum();
... etc.
我对类模板进行了部分特化,以允许重载数学运算符以实现双重特化。我现在也想将此特化扩展到 int,但不是复制用 int 替换 double 的特化,有没有办法将它添加到特化列表中?
也就是说,有没有办法允许:
template<>
class Vec<double (or) int>
干杯!
最佳答案
我想你可以使用 bool 默认值,比如 foo
以下示例中的结构
#include <iostream>
template <typename>
struct isSpecialType
{ static constexpr bool value { false }; };
template <>
struct isSpecialType<int>
{ static constexpr bool value { true }; };
template <>
struct isSpecialType<double>
{ static constexpr bool value { true }; };
template <typename T, bool = isSpecialType<T>::value>
struct foo;
template <typename T>
struct foo<T, true>
{ static constexpr bool value { true }; };
template <typename T>
struct foo<T, false>
{ static constexpr bool value { false }; };
int main()
{
std::cout << "- void value: " << foo<void>::value << std::endl;
std::cout << "- bool value: " << foo<bool>::value << std::endl;
std::cout << "- int value: " << foo<int>::value << std::endl;
std::cout << "- double value: " << foo<double>::value << std::endl;
}
这个想法是定义一种类型特征( isSpecialType
)来选择所选类型(在您的示例中为 int
和 double
), bool 值为 false
在通用实现中和 true
在专业领域。
template <typename>
struct isSpecialType
{ static constexpr bool value { false }; };
template <>
struct isSpecialType<int>
{ static constexpr bool value { true }; };
template <>
struct isSpecialType<double>
{ static constexpr bool value { true }; };
接下来您必须声明 foo
结构( class Vec
,在你的问题中)带有补充 bool
模板值与 isSpecialType<T>::value
默认值
template <typename T, bool = isSpecialType<T>::value>
struct foo;
最后,您必须实现 foo
的两个部分专用版本:第一个带有 bool 值的 true
值
template <typename T>
struct foo<T, true>
{ static constexpr bool value { true }; };
对应于你的Vec
的专业版;带有 false
的那个 bool 值
template <typename T>
struct foo<T, false>
{ static constexpr bool value { false }; };
对应于你的Vec
的通用版本.
还有一点:我的例子是C++11或者更新的代码;如果你想要一个 C++98 版本,你只需要定义 bool
值为 const
(而不是 constexpr
)并用 C++98 风格初始化它们;我是说
static bool const bool value = true;
代替
static constexpr bool value { true };
关于c++ - 多种类型的部分类模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43577471/