How to convert C++ class/struct to a primitive/different type/class/struct?

心不动则不痛 提交于 2019-12-06 14:53:21

You'd need a conversion operator:

operator const TT&(void) const
{
    return val;
}


operator TT&(void)
{
    return val;
}

There is a brief tutorial on conversion operators here. In short, when the compiler tries to convert a type, it will first look at the right-hand side for an operator that will convert it to the desired type. What we are doing is saying "Whatever TT is, this class can be converted to it".

If no operators are found, it looks to see if the left-hand side can be constructed from the right-hand side, and so on. (Until, if it cannot find a conversion, it emits an error.)


You can remove your explicitly defined default constructor if you declare your other constructor like this:

// If not specified, construct with default-constructed type.
CppProperty(TT aval = TT()) : val(aval)
{
}

You need to provide operator int() to your class to allow the implicit conversion to int.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!