tags:

views:

68

answers:

5

If I have this structure:

namespace A
{
    template <Class T>
    struct Point
    {
        Point<T>(T x_, T y_) : x(x_), y(y_) {}

        Point<T>() : x(0), y(0) {}

         T x;
         T y;
    }
}

How might I define an object from the Point struct?

I tried:

A::Point point;

but it does not work.

A: 

A::Point<int> point; for example, or A::Point<float> point; - you need to specify the type to specialize with. Otherwise how would the compiler know which type T is?

tenfour
+1  A: 

You have to specify the template argument when instantiating the structure, e.g.:

A::Point<double> point;
Frédéric Hamidi
+5  A: 

i.e.:

 A::Point<int> point;
 A::Point<int> point(1,1);

but first fix errors (note case for 'class' and missing semicolons):

namespace A
{
    template <class T>
    struct Point
    {
        Point<T>(T x_, T y_) : x(x_), y(y_) {}

        Point<T>() : x(0), y(0) {}

         T x;
         T y;
    };
}
sinec
D'oh beat me to it by 29 seconds! There's a stray ) in your first line though.
awoodland
Great! Thanks! It works!
JoesyXHN
@awoodland thanks:)
sinec
<pedant>The semicolon after the end of the namespace isn't needed</pedant>
awoodland
@awoodland fixed. Tnx!
sinec
+3  A: 

There seems to be a few syntax errors here. If you correct your code to:

namespace A
{
    template <class T> // Class is lowercase
    struct Point
    {
        Point(T x_, T y_) : x(x_), y(y_) {} // No need for <T>

        Point() : x(0), y(0) {} // No need for <T>

         T x;
         T y;
    }; // Semi colon
}

Then:

A::Point<int> point;

is valid. You need to tell it what the template parameter is though, there's no way to deduce it automatically in this case.

awoodland
awoodland
A: 

For a start you need to add a semicolon after the definition of struct Point. The to declare an instance of type A::Point<int>:

A::Point<int> point;
Joe D