简体   繁体   中英

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. Eventually allowing me to add float with int , char with int and so on!

Pointer is not a fundamental type in C++ but it I need to implement it too. 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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