C++静态运算符重载

jam*_*o00 8 c++ indexing static operator-overloading

是否可以在静态上下文中重载C++类操作符?例如

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

    Class_1[val]...

}
Run Code Online (Sandbox Code Playgroud)

Joh*_*itb 13

如果您正在寻找使用内置运算符的元编程:这样的事情是不可能的 - 内置运算符在运行时值上运行,而不是在编译时值上运行.

您可以使用boost::mpl它,而不是使用内置运算符,使用其模板,如atfor op[],plus<a, b>for op+等.

int main() {
    using boost::mpl::vector;
    using boost::mpl::at_c;
    using boost::mpl::plus;
    using boost::mpl::int_;

    typedef vector<int, bool, char, float> Class_1;
    typedef vector< int_<1>, int_<2> > Numeric_1;

    at_c<Class_1, 0>::type six = 6;
    typedef plus<at_c<Numeric_1, 0>::type 
                ,at_c<Numeric_1, 1>::type>::type r;
    int i3[r::value] = { 4, 5, 6 };
    return ((i3[0] + i3[1] + i3[2]) * six) == 90;
}
Run Code Online (Sandbox Code Playgroud)


Sam*_*war 5

我不相信这是可能的,尽管我在这方面可能是错的.我想问你为什么要这样做.您可能只需要在整个应用程序中使用一个实例,而不是对类而不是实例执行操作?在这种情况下,您可能应该使用单例模式.