dimanche 15 mars 2020

Use reference template arguments in inner class

This is my code:

template<class V, class Ref = V&>
class Util {
public:
    typedef Ref reference;
};

template<class D, class V, class Ref = V&>
class Base {
public:
    class Inner1: public Util<const V, const Ref> {
    public:
        Inner1(const D &d) :
                d(d) {
        }
        typename Inner1::reference foo() const {
            static V v;
            return v;
        }
    private:
        const D &d;
    };
    class Inner2: public Util<V, Ref> {
    public:
        Inner2(D &d) :
                d(d) {
        }
        typename Inner2::reference foo() const {
            static V v;
            return v;
        }
    private:
        D &d;
    };
};

class Child: public Base<Child, float> {
public:
    Inner1 getInner1() const {
        return Base<Child, float>::Inner1(*this);
    }
    Inner2 getInner2() {
        return Base<Child, float>::Inner2(*this);
    }
};

void print(float & ff) {

}

int main() {
    Child c;
    Child::Inner1 inner = c.getInner1();
    print(inner.foo());
    return 0;
}

This code compile without problems but I guess I should receive a compilation error. The method foo of class Inner1 should return a const reference, but for unknown reason Ref is defined without const. Why?

Aucun commentaire:

Enregistrer un commentaire