Milk3dfx
Milk3dfx

Reputation: 667

Type defined in template use to define template method of the class

There is a sample of the code:

template <class T>
class CMessage
    {
    public:
        using message_ptr = typename std::shared_ptr<T>;
        static message_ptr Create (T val)
            {
            return std::make_shared<T>(val);
            }
    };

class CBuilder
    {
    public:
        template <typename MT> MT::message_ptr CreateMessage()
            {
            return MT::message_ptr();
            }
    };

CBuilder builder;
CMessage<int>::message_ptr msg = builder.CreateMessage<CMessage<int>>();

CBuilder clsss is correct? It is possible to use MT::message_ptr in CBuilder?

Upvotes: 0

Views: 71

Answers (1)

Daniel Strul
Daniel Strul

Reputation: 1528

When you write "MT::message_ptr", you actually write an expression that depends on the definition of your parameter template (MT): that's called a dependent expression.

The problem for the compiler then is to know whether "message_ptr" is a type name or a name for something else (a function, a variable...). To solve this problem, the standard requires that any dependent expression for a type-name is prefixed by the the keyword... typename :-)

So here is the correct definition for your member function template:

template <typename MT> 
typename MT::message_ptr CreateMessage()
{
    return typename MT::message_ptr();
}

EDIT

BTW, "std::shared_ptr<T>" is not a dependent expression, so you must not use the keyword "typename" there. Simply write:

using message_ptr = std::shared_ptr<T>;

Upvotes: 1

Related Questions