c++ - 多种类型的部分类模板特化

标签 c++ templates operator-overloading template-specialization partial-specialization

我有一个类,它允许创建一个包含任何类型或类的 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 )来选择所选类型(在您的示例中为 intdouble ), 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/

相关文章:

c++ - 模板特化 - MSVC 和 GCC/MinGW 之间的不同行为

c++ - 为什么我不能重载 ostream 的 << 运算符?

c++ - 这个 bool 运算符在 C++ 中实际上做了什么?这个奇怪的东西有什么用?

c++ - 是否在没有对象未定义行为的情况下访问静态 struct::var?

c++ - GnuWin32 Make 无法运行 makefile

c++ - 递归文件搜索

c++ - 可变参数模板模板参数语法

c++ - SFINAE 不适用于 Visual Studio 2010 for std::is_pointer

c++ - 重载运算符 `[ ]` 和 ':'

c++ - 在 QTextEdit 或 Qt-Creator 的 connect() 中使用指针