【问题标题】:type casting problem with template class in C++C++中模板类的类型转换问题
【发布时间】:2011-05-24 17:11:32
【问题描述】:

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

//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.

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

【问题讨论】:

  • 当我修复琐碎的编译器错误(缺少; 等,从CUSTOMIZE_Type 中删除派生,提供WRAPPER_Int32 的定义,让i 实际引用某些东西)时,编译时没有使用 -Wall -Werror -Wextra -ansi 的 GCC 4.1.2 出现问题。所以一定有什么你没有告诉我们的!
  • 你写的代码不能编译,因为你不能有一个未初始化的引用。你的实际代码是什么样的?
  • 嗨,马克,谢谢你的评论。只是一个快速反馈,我怀疑“i”已初始化,否则,它不应该是另一种类型的错误(我发现未初始化的引用等)吗?嗯,我也会从这方面进行调查
  • 各位,非常感谢你们的 cmets。我忘记包含一个头文件。 Oli 和 Mark,我升级了你们两个 cmets。

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


【解决方案1】:

我猜你期望运算符 IntType()

class ...
    operator const IntType() const;  
}

在这里行动,当你将 i 分配给 j 时:

const WRAPPER_Int32 j = i;

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

const WRAPPER_Int32 j = (WRAPPER_Int32) i;

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    相关资源
    最近更新 更多