模板; 运算符(int)

Oli*_*ops 0 c++ templates casting operator-overloading

关于我在这里已经提到的Point结构:
模板类:ctor对函数 - >新的C++标准
是否有机会用cast-operator(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;
}  
Run Code Online (Sandbox Code Playgroud)

我认为问题在于C++无法区分不同的返回类型?提前谢谢了.关于
哎呀

ken*_*ytm 5

正确的语法是

 operator int() const {
    ...
Run Code Online (Sandbox Code Playgroud)

重载强制转换操作符时,不需要具有额外的返回类型.

当你说(int)x,编译器真的希望得到一个int,而不是一个Point<dims, int>.可能你想要一个构造函数.

 template <typename U>
 Point(const Point<dims, U>& other) { ... }
Run Code Online (Sandbox Code Playgroud)