1

I have this code and it compiles successfully.

#include <iostream>
#include <memory>
template <typename T>
class Expression {
    public:
    T _data;

    Expression() {}

    Expression(T data) {
        _data = data;
    }
    void foo();
};



template <typename T>
class ConstExpression : public Expression<T> {
    public:
    ConstExpression() {}
    ConstExpression(T data) {
        this->_data = data;
    }
};


template <typename T>
void Expression<T>::foo() {
    std::shared_ptr<ConstExpression<T>> temp(new Expression);
    std::shared_ptr<ConstExpression<T>> temp2(new ConstExpression<T>());
    ConstExpression<T> foo2(5);
}

int main() {
    return 0;
}

Now if I do the following or give my function foo an input argument of type constexpression I get an error: main.cc:15:25: error: use of undeclared identifier 'ConstExpression'; did you mean 'Expression'? In my real code my function takes an input argument of type ConstExpression and I have done an out of line declaration too but get a similar error.

#include <iostream>
#include <memory>
template <typename T>
class Expression {
    public:
    T _data;

    Expression() {}

    Expression(T data) {
        _data = data;
    }
    void foo() {
        std::shared_ptr<ConstExpression<T>> temp(new Expression);
        std::shared_ptr<ConstExpression<T>> temp2(new ConstExpression<T>());
        ConstExpression<T> foo2(5);
    }
};



template <typename T>
class ConstExpression : public Expression<T> {
    public:
    ConstExpression() {}
    ConstExpression(T data) {
        this->_data = data;
    }
};

int main() {
    return 0;
}
pizzaEatingGuy
  • 878
  • 3
  • 10
  • 19
  • You need to use forward declaration. Have a look at this post http://stackoverflow.com/questions/553682/when-to-use-forward-declaration – Santanu C Nov 29 '13 at 06:57
  • This: `std::shared_ptr> temp(new Expression);` wouldn't be legal even if the other problems are solved. `Expression` is a template and you're providing no template parameter, and even if you were, it isn't a derivation of `ConstExpression`; rather its the other way around. – WhozCraig Nov 29 '13 at 07:03
  • The REAL problem (besides the aforementioned problems) is that you have a base class that knows about a derived class. It seems like inheritance isn't the right solution to the problem you are trying to solve. – KSletmoe Nov 29 '13 at 07:10

1 Answers1

1

In the Expression class you use ConstExpression, but ConstExpression havent been declared yet.

You can overcome this by a forward declaration of the ConstExpression before its use:

template<typename T>
class ConstExpression;

template<typename T>
class Expression { ... };
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621