C++表达式模板:运算符是什么?
template <typename E>
class VecExpression{
public:
operator E&(){
return static_cast<E&>(*this);
}
operator E const&() const{
return static_cast<const E&>(*this);
}
};
有人可以向我解释一下这段代码吗?我从未见过这种运算符重载。它的返回类型是什么?它有什么参数吗?我可以看到用法或者它在源代码中被调用的位置吗?
template <typename E>
class VecExpression{
public:
operator E&(){
return static_cast<E&>(*this);
}
operator E const&() const{
return static_cast<const E&>(*this);
}
};
could someone please explain to me this code? I've never seen this kind of operator overloading. What is its return type? Does it have any parameters? Can I see a usage or maybe where it's getting called in the source?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
VecExpression
是一个模板,因此运算符返回对该类的模板类型E
的常量或非常量引用。它是一个隐式转换运算符。它不接受任何参数,仅使用VecExpression
并允许在需要E
的上下文中使用它。VecExpression
is a template so the operators are returning a const or non-const reference to the template typeE
of the class. It's an implicit conversion operator. It takes no parameters, just takes a use ofVecExpression<E>
and allows its use in a context where it needs anE
.这是转换运算符。
这将调用::operator int()
This is the conversion operator.
that would invoke a::operator int()
您可以将其视为强制转换运算符。
它将 VecExpression 定义为类型 E 的对象(或对类型 E 的对象的引用)。基本上,这允许您将 VecExpression 类型的对象传递给任何采用 E 类型对象的函数,并且编译器将使用此运算符自动转换。
You can think of it as the cast operator.
It is defining the cast VecExpression to an object of type E (or a reference to object of type E). Basically this allows you to pass an object of type VecExpression to any function that takes an object of type E and the compiler will auto convert using this operator.