views:

95

answers:

1

Hi,
regarding my Point struct already mentioned here:
http://stackoverflow.com/questions/2794369/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

+5  A: 

The correct syntax is

 operator int() const {
    ...

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 an int, not a Point<dims, int>. Probably you want a constructor instead.

 template <typename U>
 Point(const Point<dims, U>& other) { ... }
KennyTM
Yes! thanks, this is probably the best solution. no other answer is needed.
Oops
Alternative correct syntax: `operator Point<dims, int>()` ;) But using a constructor for conversion is a better idea.
UncleBens