1

I have a class template like Sample.hpp with type alias X.

#ifndef SAMPLE_HPP
#define SAMPLE_HPP

template<typename STA, typename STB>
class Sample
{
    using X = Sample<STA,STB>;

public:
    Sample();
    inline X* GetNext() const;

private:
    X* Next;
};

#include "Sample.cpp"

#endif // SAMPLE_HPP

And definitions are in Sample.cpp.

#include "Sample.hpp"

template<typename STA, typename STB>
Sample<STA,STB>::Sample() {
    Next = nullptr;
}

template<typename STA, typename STB>
typename Sample<STA,STB>::X* Sample<STA,STB>::GetNext() const {
    return this->Next;
}

My question is that, are there any others ways of defining GetNext function. For example without typename or without full declaration of Sample class template. When I change code to

template<typename STA, typename STB>
Sample<STA,STB>* Sample<STA,STB>::GetNext() const {
    return this->Next;
}

It works, but I cant use type alias here directly , for example :

template<typename STA, typename STB>
X* Sample<STA,STB>::GetNext() const {
    return this->Next;
}

1 Answer 1

5

You can use a trailing return type with the help of auto:

template<typename STA, typename STB>
auto Sample<STA, STB>::GetNext() const -> X* {
    return this->Next;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, can you please explain this in more detail?
@CherkesgillerTural Sure thing. So if you put X* at the start, the compiler has no way of knowing that X is supposed to be, so you get an error. But if you write it after, then the compiler can look in the scope of Sample<STA, STB> for X. If you put it before, it didn't encounter Sample<STA, STB> yet, so it can't look for X there. More information about that here.
Thank you very much, @Rakete111.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.