Dimitrije Kostic
Dimitrije Kostic

Reputation: 305

Compiler fails to recognize a templated class

This is a very stripped-down version of some code I have that fails to compile.

template <typename name_of_type_t> class classA_t
{ /* etc etc etc */ };

template <typename name_of_type_t> class classB_t 
{
    public:
        classA_t<name_of_type_t> && return_new();
};

classA_t<name_of_type_t> && classB_t::return_new() // <-- errors here
{
    classA_t<name_of_type_t> * S = new classA_t<name_of_type_t>;
    return std::move(*S);
}

int main() { return 0; }

The compiler error I get is

template_error.cpp:12:10: error: use of undeclared identifier 'name_of_type_t'
classA_t<name_of_type_t> && classB_t::return_new()
         ^
template_error.cpp:12:29: error: 'classB_t' is not a class, namespace, or enumeration
classA_t<name_of_type_t> && classB_t::return_new()
                            ^
template_error.cpp:4:42: note: 'classB_t' declared here
template <typename name_of_type_t> class classB_t 
                                         ^
2 errors generated.

If name_of_type_t is undeclared, why didn't the compiler flag my earlier uses of it? What does the compiler think classB_t is, if not a class?

Upvotes: 1

Views: 63

Answers (1)

songyuanyao
songyuanyao

Reputation: 172894

classB_t is a template. When declaring its member function out of the class definition, you need to declare the template parameter list again, and specify the template parameters in the class type, e.g.

template <typename name_of_type_t>
classA_t<name_of_type_t> && classB_t<name_of_type_t>::return_new()
{
    classA_t<name_of_type_t> * S = new classA_t<name_of_type_t>;
    return std::move(*S);
}

Upvotes: 5

Related Questions