Home>

I am studying templates in C ++.
If i add a constructor with arguments,
Can it be used as a class constant?

In the following cases, a type specifier is required.

Thanks for your teaching.

Applicable source code
template<typename T>
struct VECTOR {
    T x, y, z;
    VECTOR () = default;
    VECTOR (T x, T y, T z) {this->x = x;this->y = y;this->y = z;}
// Other various operators
};
class Test {
private:
// constexpr?
    static const VECTOR<int>pos (100,100,100);
};
  • Answer # 1

    You can defineinitializationfor static member variables.

    class Test {
    private:
        static const VECTORpos;
    };
    const VECTORTest :: pos (100,100,100);

    Alternatively, by specifyinginlineafter C ++ 17

    class Test {
    private:
        static inline const VECTORpos {100,100,100};
    };

    is also possible.


    In addition, it is possible to specifyconstexprto the constructor.

    template
    struct VECTOR {
        T x, y, z;
        VECTOR () = default;
        constexpr VECTOR (T x, T y, T z): x (x), y (y), z (z) {}
    };
    class Test {
    private:
        static constexpr VECTORpos = {100,100,100};
    };

  • Answer # 2

    The third constexpr specification has solved it!
    Thank you for teaching us various solutions!