C ++模板类和复制构造

时间:2010-04-04 16:03:52

标签: c++ templates

如果两个对象的模板参数在运行时相同,是否可以从给定对象构造新对象?例如:

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

template<typename _Type1, typename _Type2> class Object;

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

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

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

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>
    }
}

我尝试了几种技术,例如在__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

我无法做到这一点吗?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分: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;
}

这是一个免费的功能,你可以看到。你可以把它作为一个成员函数来做,但它更棘手,因为你不能专门化个别成员函数 - 你必须专门化整个类。您可以通过分解非专业代码来解决这个问题,但这非常难看,而且这也很有效。