是否可以重载* static_cast *运算符? [英] Is it possible to overload the *static_cast* operator?
问题描述
我定义了一个类 A ,实际的属性无关紧要。是否可以定义 static_cast< class T>(int)
运算符的特殊化,以将整数转换为A类?
I have defined a class A, the actual properties are irrelevant. Is it possible to define a specialization of the static_cast<class T>(int)
operator to convert from integers to class A?
到目前为止,我一直在通过定义 convert 函数来做到这一点,例如 convert(int)
。但是我宁愿使用 static_cast
与其他转化保持一致。
So far I have been doing this by defining a convert function, such as A convert(int)
. But I would rather use static_cast
for consistency with other conversions.
有可能吗?
我还想避免隐式转换,这就是为什么我不通过 A做到这一点
Is it possible?
I also want to avoid implicit conversions, which is why I'm not doing this through A's constructor.
推荐答案
static_cast
是语言关键字,您无能为力。但是,您可以 使用显式转换构造函数实现目标:
static_cast
is a language keyword and you can't do anything to change that. However you can achieve what you what with an explicit converting constructor:
class Foo
{
public:
explicit Foo(int bar) { } // Can't be called implicitly, CAN be invoked with `static_cast`.
};
之所以有效,是因为该语言定义了 static_cast
'对象构造方面的行为,并酌情调用转化。
This works because the language defines static_cast
's behavior in terms of object construction, invoking conversions as appropriate.
这篇关于是否可以重载* static_cast *运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!