0

Here is this class:

template<typename T>
class TestClass
{
private:
    struct element
    {
        T data;
        element* ptr;

        explicit element(T val) : data(val), ptr (nullptr) {}
    };
    element entity;

public:
    T foo(int);
    void fee(const TestClass&);
    element* faa(T, bool order = true);

    explicit TestClass(T p1);
    ~TestClass() {}
};

while I tried defining the following function outside the class as:

template<typename T>
TestClass<T>::element* TestClass<T>::faa(T val, bool order)
{
    //blah blah blah
}

I got the following error: (compiling on this site)

main.cpp:36:1: error: need ‘typename’ before ‘TestClass::element’ because ‘TestClass’ is a dependent scope
   36 | TestClass<T>::element* TestClass<T>::faa(T val, bool order)
      | ^~~~~~~~~~~~
      | typename 

I tried searching on stack overflow - got THIS page. But I am still not understanding where is my error. Kindly advice.

SogaBan
  • 15
  • 5
  • 1
    [Here is a link to a more appropriate post](https://stackoverflow.com/q/610245/631266) – Avi Berger Aug 24 '22 at 01:05
  • Did you try doing exactly what the error message tells you to do? – Sam Varshavchik Aug 24 '22 at 01:13
  • Still couldn't understand - what is wrong with my syntax. Please point out. – SogaBan Aug 24 '22 at 01:21
  • `typename` is a keyword that you need to tell the compiler how to parse your `faa` definition properly. The compiler error says this exactly. As a side question, how exactly does one use a pointer to a private struct outside of class definition? – dmedine Aug 24 '22 at 01:21
  • @SamVarshavchik > I am unable to understand - "before" part of the error message. Because there is already a 'typename T' before TestClass::element – SogaBan Aug 24 '22 at 01:23
  • The third line of the compiler error uses the `^` character to indicate the exact position it wants to see `typename`. It's really rather helpful ;-). – dmedine Aug 24 '22 at 01:25
  • @dmedine - answer to your side question - this faa function is supposed to be a private member function. Sorry, for the typo. – SogaBan Aug 24 '22 at 01:27
  • The line with the error should begin with `typename TestClass::element`… – Pete Becker Aug 24 '22 at 01:29
  • template typename TestClass::element* TestClass::faa(T val, bool order); ---- solved my problem - but I am unable to grasp the significance of my error/mistake of my conception!! Even after going through the dissertation mention by @AviBerger – SogaBan Aug 24 '22 at 01:30
  • 1
    Welcome to C++, the linked question explains it. I wouldn't call this an error or an oversight, this is just a missing bit of understanding of an arkane part of C++'s complicated syntax. After making the same error a few times one will often instinctively learn when and where to shove an extra `typename`, in the right place. – Sam Varshavchik Aug 24 '22 at 01:35

0 Answers0