use*_*460 6 c++ templates operator-overloading partial-specialization template-specialization
我有一个类,允许创建包含任何类型或类的向量。不过,我想为数字类型添加附加功能。
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.
Run Code Online (Sandbox Code Playgroud)
我已经部分专门化了类模板,以允许重载数学运算符以实现双重专门化。我现在也想将此专业化扩展到 int ,但不是复制专业化以 int 替换 double ,有没有办法将其添加到专业化列表中?
也就是说,有没有办法允许:
template<>
class Vec<double (or) int>
Run Code Online (Sandbox Code Playgroud)
干杯!
我想你可以使用布尔默认值,就像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;
}
Run Code Online (Sandbox Code Playgroud)
这个想法是定义一种类型特征 ( isSpecialType) 来选择所选类型(在您的示例中为int和double),其布尔值位于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 }; };
Run Code Online (Sandbox Code Playgroud)
接下来,您必须使用带有默认值的补充模板值来声明foo结构(在您的问题中)class VecboolisSpecialType<T>::value
template <typename T, bool = isSpecialType<T>::value>
struct foo;
Run Code Online (Sandbox Code Playgroud)
最后,您必须实现两个部分专用的版本foo:第一个具有布尔true值
template <typename T>
struct foo<T, true>
{ static constexpr bool value { true }; };
Run Code Online (Sandbox Code Playgroud)
对应于您的专用版本Vec;false具有布尔值的那个
template <typename T>
struct foo<T, false>
{ static constexpr bool value { false }; };
Run Code Online (Sandbox Code Playgroud)
对应于您的通用版本Vec。
还有一点:我的例子是C++11或更新的代码;如果您想要 C++98 版本,您只需将bool值定义为const(而不是constexpr) 并以 C++98 样式初始化它们;我是说
static bool const bool value = true;
Run Code Online (Sandbox Code Playgroud)
代替
static constexpr bool value { true };
Run Code Online (Sandbox Code Playgroud)