我有一个特殊的类,我想为它写一个类型转换操作符,但是我不能直接修改类代码。
的例子:
class MyClass; // not modifyable
class MyClass
{
// can't do this
operator AnotherType () const
{
AnotherType t;
t.setSomething();
return t;
}
}
MyClass m;
static_cast<AnotherType> m; // want to be able to do this
是否有可能将static_cast
调用的东西表示为外部函数?
这是我的尝试,它没有工作,我不期望工作。
operator AnotherType(MyClass m)
{
AnotherType t;
t.setSomething();
return t;
}
编译器产生的错误表明static_cast
正在为AnotherType
寻找一个以MyClass
为参数的构造函数。这表明了一种可能的替代方法,即编写转换构造函数。只有当要转换为可修改的类型时,这才会起作用。
也可以编写一个外部函数,在不使用转换构造函数的情况下进行转换。但是static_cast
不会调用。
,
AnotherType convertFunction(MyClass) {...}
还有另一种解决方案,即使用Adapter模式,并在Adapter类中编写类型转换操作符。对于我来说,这可能是唯一的解决方案。
如果你不能改变A
和B
,你就不能让A a; static_cast<B>(a);
工作。
如果你能定义Something
,你可以让A a; B b = static_cast<Something>(a);
工作。
在coliru上看