Search code examples
c++classtemplatesvariable-declaration

Set a class static


I'm trying to write a class as an exercise and have the following:

template <class Foo>
class Bar
{
protected:
    Foo _x,_y,_z;
public:
    Bar(Foo x, Foo y, Foo z) {_x=x; _y=y; _z=z;};
    Bar() {_x=0; _y=0; _z=0;};

    static const Bar<Foo> X;
};

I'll like to initialise X as (0,1,0) but have no idea how to do so. I would like declare X =(0,1,0) to be like declaring #define pi = 3.142 at the start of a program. How should I go about doing this?


Solution

  • What you've done is fine, but you're probably getting a linker error as you're not providing any storage for X. You need to do this:

    template <class Foo>
    class Bar
    {
    protected:
        Foo _x,_y,_z;
    public:
        Bar(Foo x, Foo y, Foo z) {_x=x; _y=y; _z=z;};
        Bar() {_x=0; _y=0; _z=0;};
    
        static const Bar<Foo> X;
    };
    
    template <typename Foo>
    const Bar<Foo> Bar<Foo>::X(0, 1, 0);
    

    Unlike non-template static variables, this is fine to go in a header -- as with other templates, duplicate definitions of Bar<Foo>::X will be merged at link-time.