C ++中模板类的类型转换问题

时间:2011-05-24 17:11:32

标签: c++ templates casting operator-overloading type-conversion

我不是模板或类型转换专家,所以我真的需要一些帮助。 我必须使用现有的模板类并遇到以下类型转换问题。 我提供了一些示例代码来说明问题。

//template class definition
template <class IntType>
class CUSTOMIZE_Int: public CUSTOMIZE_Type
{
 public:
     operator const IntType() const;  
 private:
     IntType m_int;
}

template<class IntType>
CUSTOMIZE_Int<IntType>::operator const IntType() const
{
   return m_int;  
}

// the template class instantiation
typedef CUSTOMIZE_Int<WRAPPER_Int32> CUSTOMIZE_UnsignedInt;

然后在我的代码中,我派生了一个新类

// the derived class definition
class IntNum: public CUSTOMIZE_UnsignedInt
{
    // ctors and new methods;
}

并创建一个变量,并尝试进行转换以获取数据。

class IntNum& i;
const WRAPPER_Int32 j = i;

出现以下编译错误:

error: cannot convert "IntNum" to "const WRAPPER_Int32" in initialization.

进行转换的正确方法是什么,或者我的代码有什么问题? 感谢您的任何评论!

1 个答案:

答案 0 :(得分:-1)

我猜您希望运算符IntType()

class ...
    operator const IntType() const;  
}
当你把我分配到j:

时,

在这里行动

const WRAPPER_Int32 j = i;

但是,这不是隐式转换,您必须明确地执行:

const WRAPPER_Int32 j = (WRAPPER_Int32) i;

希望这有帮助。