简体   繁体   English

为部分特化类特化成员函数

[英]Specialize member function for partially specialized class

I'm writing a class that holds fundamental types and call basic operators for scalar types.我正在编写一个包含基本类型并为标量类型调用基本运算符的类。

template<typename _Ty>
class Fundamental {
    using DataType = _Ty;
public:        
    Fundamental(const DataType& value): value(value) {}
    operator DataType() { return value; }
    
    template<typename _Ty2>
    void operator+=(_Ty2 value) { this->value += value; }

    DataType value;
}

I made operator+= a template so it can take any value rather than just DataType.我制作了operator+=模板,因此它可以采用任何值而不仅仅是 DataType。 Eventually allowing me to add float with int , char with int and so on!最终允许我添加floatintcharint等等!

Pointer is not a fundamental type in C++ but it I need to implement it too.指针不是 C++ 中的基本类型,但我也需要实现它。 Pointer type however should only be added and subtracted with a integer (That's what I need).然而,指针类型只能用整数加减(这就是我需要的)。 So, to do that I thought of partially specializing my class for pointer and fully specialize operator+= to take int like所以,要做到这一点,我想到了部分专门化我的指针类并完全专门化operator+=以采用int之类

template<>
template<typename _Ty>
void Fundamental<_Ty*>::operator+=(int value) { this->value += value; }

This however doesn't work and compiler complains然而这不起作用并且编译器抱怨

Fundamental<_Ty*>::operator +=': unable to match function definition to an existing declaration

How do I make the operator accept only integer for pointers?如何让操作员只接受整数作为指针?

I tried using-declaration我尝试使用声明

template<typename T>
using Param = typename std::conditional<std::is_pointer<DataType>::value, int, T>::type;

template<typename _Ty>
void operator+=(Param<_Ty> value) { this->value += value; }  

Error occurs saying '... does not define this operator ...'.出现错误说'...没有定义此运算符...'。

Template specialization does not remove the default template, it just makes one "special".模板专业化不会删除默认模板,它只是使一个“特殊”。

Now you could probably make the default one invalid using some SFINAE but the right approach is to simply leave out the template from your pointer specialization and use a plain, int-only method.现在,您可能可以使用一些 SFINAE 使默认值无效,但正确的方法是简单地从您的指针特化中省略模板并使用简单的、仅限 int 的方法。

template<class T>
class Fundamental<T*> {
   //...
   // not a template
   void operator += (int x) { ... }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM