Why can't I inherit from int in C++?

前端 未结 19 2208
不知归路
不知归路 2020-12-02 18:24

I\'d love to be able to do this:

class myInt : public int
{

};

Why can\'t I?

Why would I want to? Stronger typing. For example, I

19条回答
  •  执笔经年
    2020-12-02 18:35

    As others I saying, can't be done since int is a primitive type.

    I understand the motivation, though, if it is for stronger typing. It has even been proposed for C++0x that a special kind of typedef should be enough for that (but this has been rejected?).

    Perhaps something could be achieved, if you provided the base wrapper yourself. E.g something like the following, which hopefully uses curiously recurring templates in a legal manner, and requires only deriving a class and providing a suitable constructor:

    template 
    class Wrapper
    {
        T n;
    public:
        Wrapper(T n = T()): n(n) {}
        T& value() { return n; }
        T value() const { return n; }
        Child operator+= (Wrapper other) { return Child(n += other.n); }
        //... many other operators
    };
    
    template 
    Child operator+(Wrapper lhv, Wrapper rhv)
    {
        return Wrapper(lhv) += rhv;
    }
    
    //Make two different kinds of "int"'s
    
    struct IntA : public Wrapper
    {
        IntA(int n = 0): Wrapper(n) {}
    };
    
    struct IntB : public Wrapper
    {
        IntB(int n = 0): Wrapper(n) {}
    };
    
    #include 
    
    int main()
    {
        IntA a1 = 1, a2 = 2, a3;
        IntB b1 = 1, b2 = 2, b3;
        a3 = a1 + a2;
        b3 = b1 + b2;
        //a1 + b1;  //bingo
        //a1 = b1; //bingo
        a1 += a2;
    
        std::cout << a1.value() << ' ' << b3.value() << '\n';
    }
    

    But if you take the advice that you should just define a new type and overload the operators, you might take a look at Boost.Operators

提交回复
热议问题