Home > Software engineering >  How to correctly define a template class return type of a template function?
How to correctly define a template class return type of a template function?

Time:10-26

What I'm trying to do is fairly simple. I have a template class PayloadResult<T> with a generic payload and in another class a template function which returns an object of such class.

class Result
{
public:
    template<class TPayload>
    PayloadResult<TPayload> success(TPayload payload) { return PayloadResult<TPayload>(payload); }
}



template <TPayload>
class PayloadResult
{
private:
    TPayload payload_;

public:
    PayloadResult(TPayload payload)
    {
        payload_ = payload;
    }

    TPayload payload()
    {
        return payload;
    }
}

What happens is that the compiler tells me that the success function's return type is No template named 'PayloadResult'

I changed the return type signature to std::array<TPayload, 1> and it worked. What am I doing wrong? (I am a newbie in C )

Many thanks in advance!

CodePudding user response:

Below is the corrected example. You have to forward declare the class template PayloadResult<> for using it as the return type as you did in your example. Second you did not have the keyword typename or class infront of TPayload.

//forward declare the class template PayloadResult
template <typename TPayload> class PayloadResult;

class Result
{
public:
    template<class TPayload>
    PayloadResult<TPayload> success(TPayload payload) { return PayloadResult<TPayload>(payload); }//now this won't give error because you have forward declared 
};


//added typename
template <typename TPayload>
class PayloadResult
{
private:
    TPayload payload_;

public:
    PayloadResult(TPayload payload)
    {
        payload_ = payload;
    }

    TPayload payload()
    {
        return payload;
    }
};
int main()
{
    return 0;
}
  • Related