开发者

How to define an object of a templated class type?

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 开发者_JAVA技巧object from the Point struct?

I tried:

A::Point point;

but it does not work.


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;
    };
}


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.


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

A::Point<double> point;


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?


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜