模板;运算符(整数)
关于我的 Point 结构已经在这里提到:
模板类:针对函数的 ctor ->新的C++标准
是否有机会用强制转换运算符 (int) 替换函数 toint() ?
namespace point {
template < unsigned int dims, typename T >
struct Point {
T X[ dims ];
//umm???
template < typename U >
Point< dims, U > operator U() const {
Point< dims, U > ret;
std::copy( X, X + dims, ret.X );
return ret;
}
//umm???
Point< dims, int > operator int() const {
Point<dims, int> ret;
std::copy( X, X + dims, ret.X );
return ret;
}
//OK
Point<dims, int> toint() {
Point<dims, int> ret;
std::copy( X, X + dims, ret.X );
return ret;
}
}; //struct Point
template < typename T >
Point< 2, T > Create( T X0, T X1 ) {
Point< 2, T > ret;
ret.X[ 0 ] = X0; ret.X[ 1 ] = X1;
return ret;
}
}; //namespace point
int main(void) {
using namespace point;
Point< 2, double > p2d = point::Create( 12.3, 34.5 );
Point< 2, int > p2i = (int)p2d; //äähhm???
std::cout << p2d.str() << std::endl;
char c; std::cin >> c;
return 0;
}
我认为问题就在这里,C++无法区分不同的返回类型?非常感谢。 问候
哎呀
regarding my Point struct already mentioned here:
template class: ctor against function -> new C++ standard
is there a chance to replace the function toint() with a cast-operator (int)?
namespace point {
template < unsigned int dims, typename T >
struct Point {
T X[ dims ];
//umm???
template < typename U >
Point< dims, U > operator U() const {
Point< dims, U > ret;
std::copy( X, X + dims, ret.X );
return ret;
}
//umm???
Point< dims, int > operator int() const {
Point<dims, int> ret;
std::copy( X, X + dims, ret.X );
return ret;
}
//OK
Point<dims, int> toint() {
Point<dims, int> ret;
std::copy( X, X + dims, ret.X );
return ret;
}
}; //struct Point
template < typename T >
Point< 2, T > Create( T X0, T X1 ) {
Point< 2, T > ret;
ret.X[ 0 ] = X0; ret.X[ 1 ] = X1;
return ret;
}
}; //namespace point
int main(void) {
using namespace point;
Point< 2, double > p2d = point::Create( 12.3, 34.5 );
Point< 2, int > p2i = (int)p2d; //äähhm???
std::cout << p2d.str() << std::endl;
char c; std::cin >> c;
return 0;
}
I think the problem is here that C++ cannot distinguish between different return types? many thanks in advance.
regards
Oops
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正确的语法是
当您重载强制转换运算符时,不需要额外的返回类型。
当您说
(int)x
时,编译器实际上希望获得一个int
,而不是Point
。也许您需要一个构造函数。The correct syntax is
There's no need to have that extra return type when you overload the cast operator.
And when you say
(int)x
, the compiler really expects to get anint
, not aPoint<dims, int>
. Probably you want a constructor instead.