Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No class template named X in templated class

When tryin to compile this (CRTP-like) code with GCC 4.6.0:

template<template<class> class T> struct A;

template<class T> 
struct B: A<B<T>::template X> {
    template <class U> struct X { U mem; };
};

B<int> a;

I get the errormessage "test.cpp:3:26: error: no class template named ‘X’ in ‘struct B<int>’". Why does X seem to be invisible outside the class definition?

like image 360
Tom De Caluwé Avatar asked Apr 26 '11 17:04

Tom De Caluwé


People also ask

How do I force a template instantiation?

To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>(float original); Template arguments may be omitted when the compiler can infer them.

What does template <> mean in C++?

Templates are a feature of the C++ programming language that allows functions and classes to operate with generic types. This allows a function or class to work on many different data types without being rewritten for each one.

Can a non-template class have a template member function?

A non-template class can have template member functions, if required. Notice the syntax. Unlike a member function for a template class, a template member function is just like a free template function but scoped to its containing class.


1 Answers

As Emile Cormier correctly points out here the problem is that at the place of instantiation of A, B is still an incomplete type, and you cannot use the inner template.

The solution for that is moving the template X outside of the template B. If it is independent of the particular instantiation T of the template B, just move it to the namespace level, if it is dependent on the instantiation, you can use type traits:

template <typename T>
struct inner_template 
{
   template <typename U> class tmpl { U mem; }; // can specialize for particular T's
};
template <typename T>
struct B : A< inner_template<T>::template tmpl >
{
};
like image 198
David Rodríguez - dribeas Avatar answered Nov 07 '22 01:11

David Rodríguez - dribeas