C ++ Template Classes and Copying

Is there a way to build a new object from this object if the template parameters of both objects are the same at run time? For instance:

I have a template class with a declaration:

template<typename _Type1, typename _Type2> class Object;

Then I have two instances of the template:

template class Object<char, int>;
template class Object<wchar_t, wint_t>;

Now I want to write a member function, for example:

template<typename _Type1, typename _Type2>
Object<char, int> Object<_Type1, _Type2>::toCharObject() {
    if(__gnu_cxx::__are_same<_Type1, char>::__value)
        return *this;
    else {
        //Perform some kind of conversion and return an Object<char, int>
    }
}

I tried a couple of methods, for example, using __gnu_cxx::__enable_if<__gnu_cxx::__are_same<_Type1, char>::__value, _Type1>::__typein the copy constructor for the class Oject, but I continue to work with an error:

error: conversion from ‘Object<wchar_t, wint_t>’ to non-scalar type ‘Object<char, int>’ requested

I can not do it? Any help would be greatly appreciated!

+5
source share
1 answer

, , return *this, (, ). return (Object<char, int>)(*this);, - , , , , .

:

template <class _Type1, class _Type2>
Object<char, int> toCharObject(Object<_Type1, _Type2> obj)
{
  // Do conversion and return
}

// Specialisation when types are equal
template <>
Object<char, int> toCharObject(Object<char, int> obj)
{
  return obj;
}

, . -, , - - . , , , .

+4

All Articles