C++模板类和复制构造

the*_*ine 5 c++ templates

如果两个对象的模板参数在运行时是相同的,我有没有办法从给定对象构造一个新对象?例如:

我有一个带声明的模板类:

template<typename _Type1, typename _Type2> class Object;
Run Code Online (Sandbox Code Playgroud)

接下来,我有两个模板实例:

template class Object<char, int>;
template class Object<wchar_t, wint_t>;
Run Code Online (Sandbox Code Playgroud)

现在,我想编写一个成员函数,例如:

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>
    }
}
Run Code Online (Sandbox Code Playgroud)

我尝试了几种技术,比如__gnu_cxx::__enable_if<__gnu_cxx::__are_same<_Type1, char>::__value, _Type1>::__type在类的复制构造函数中使用Oject,但我一直遇到错误:

error: conversion from ‘Object<wchar_t, wint_t>’ to non-scalar type ‘Object<char, int>’ requested
Run Code Online (Sandbox Code Playgroud)

我不能这样做吗?任何帮助将不胜感激!

Pet*_*der 4

你所拥有的应该可以工作,问题是编译器正在对部件进行类型检查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;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,这是一个免费功能。您可以将其作为成员函数来执行,但这更加棘手,因为您无法专门化单个成员函数——您必须专门化整个类。您可以通过分解非专用代码来解决这个问题,但这确实很丑陋,但这也同样有效。