c++c++11c++builder-xevisual-c++-2013

Overload operator += in template class with std::enable_if metafunction


I have a string class implemented as a class template like:

template <class T>
class HGStringBasic
{
//...
public:
//...
    HGStringBasic& operator += (const T* rhs)
    {
        //...
    }

    template <class U, std::enable_if_t<std::is_same<U, char>::value>* = nullptr>
    HGStringBasic& operator += (const U* rhs)
    {
        //...
    }
//...   
}

The code is C++ 11 standard conform. The goal was to implement an overloaded operator += (const char) which is only used, if class T of the template is for instance "wchar_t".

I would like to know, how i can achieve the same result if the compiler don't understand C++11.

UPDATE: Sry i'm new to stackoverlow and i haven't seen, that my code wasn't fully shown in the code block. I have now updated my code sniped so far. I have also corrected a mistake within the template argument list from the template function operator += (), TartanLlama you're absolutly right, is_same<T, char> must be is_same<U, char>.


Solution

  • Now i have figured it out, no c++11 and with the already known metafunctions. Big thanks to Barry for the hint with specifying the return type.

    Here is what i did:

    #include <type_traits>
    
    template <class _ElemT>
    class HGStringBasic
    {
        public:
            // Append char* or wchar_t* depending on specialization
            HGStringBasic& operator += (const _ElemT* rhs)
            {
                return *this;
            }
    
            // Allow char* if specialization is wchar_t
            template <class U>
            typename std::enable_if<std::is_same<U, char>::value, HGStringBasic&>::type operator += (const U* rhs)
            {
                // Convert ansistring to widestring
                return *this;
            }
    
            // Allow wchar_t* if specialization is char
            template <class U>
            typename std::enable_if<std::is_same<U, wchar_t>::value, HGStringBasic&>::type operator += (const U* rhs)
            {
                // Convert widestring to ansistring
                return *this;
            }
    };