Static constexpr of class inside class link problems

前端 未结 4 754
花落未央
花落未央 2021-01-21 06:27

I\'m trying to create static constexprs defined inside the class. I know about this question: static constexpr member of same type as class being defined, and metho

4条回答
  •  醉话见心
    2021-01-21 06:57

    In addition to Guillaume Racicot's answer you can add constexpr function that return copy or const reference to constexpr values, that defines in some other place. Or call constructor and return new instane every time, without keep constexpr variables. Tested on VS2015:

    class foo {
        int _x;
        constexpr foo(int x) : _x(x) {}
        struct constants;
    public:
    
        constexpr int x() const { return _x; }
    
        static constexpr const foo &a();
        static constexpr const foo &b();
        static constexpr const foo &c();
        static constexpr foo d() { return foo(5); }
    };
    
    struct foo::constants {
        constexpr static foo a = foo{ 1 }, b = foo{ 2 }, c = foo{ 1 };
    };
    
    constexpr const foo &foo::a() { return constants::a; }
    constexpr const foo &foo::b() { return constants::b; }
    constexpr const foo &foo::c() { return constants::c; }
    

    Then you can get values from the foo's scope, for example: static_assert(foo::a().x()==1,"");

提交回复
热议问题