C++ static operator overloading

后端 未结 4 820
无人及你
无人及你 2021-02-15 17:06

Is it possible to overload C++ class operators in the static context? e.g.

class Class_1{ ... }
int main()
{

    Class_1[val]...

}
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-15 17:40

    If you are looking for metaprogramming using the built-in operator: Such a thing isn't possible - the built-in operators operate on runtime values, not on compile time values.

    You may use boost::mpl for that, and instead of using the built-in operators, use its templates, like at for op[], plus for op+ etc.

    int main() {
        using boost::mpl::vector;
        using boost::mpl::at_c;
        using boost::mpl::plus;
        using boost::mpl::int_;
    
        typedef vector Class_1;
        typedef vector< int_<1>, int_<2> > Numeric_1;
    
        at_c::type six = 6;
        typedef plus::type 
                    ,at_c::type>::type r;
        int i3[r::value] = { 4, 5, 6 };
        return ((i3[0] + i3[1] + i3[2]) * six) == 90;
    }
    

提交回复
热议问题