Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot refer to a template name nested in a template parameter

Tags:

c++

I have the following code:

template <typename Provider>
inline void use()
{
    typedef Provider::Data<int> D;
}

Where I'm basically trying to use a template class member 'Data' of some 'Provider' class, applied to 'int', but I get the following errors:

util.cpp:5: error: expected init-declarator before '<' token
util.cpp:5: error: expected `,' or `;' before '<' token

I'm using GCC 4.3.3 on a Solaris System.

like image 709
chila Avatar asked May 18 '10 19:05

chila


People also ask

What is a template template parameter in C++?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

How do I restrict a template type in C++?

There are ways to restrict the types you can use inside a template you write by using specific typedefs inside your template. This will ensure that the compilation of the template specialisation for a type that does not include that particular typedef will fail, so you can selectively support/not support certain types.

How do you call a template function in C++?

A function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.

Which parameter is legal for non-type template?

Which parameter is legal for non-type template? Explanation: The following are legal for non-type template parameters:integral or enumeration type, Pointer to object or pointer to function, Reference to object or reference to function, Pointer to member.


2 Answers

typedef typename Provider::template Data<int> D;

The problem is that, when the compilers parses use() for the first time, it doesn't know Provider, so it doesn't know what Provider::Data refers to. It could be a static data member, the name of a member function or something else. That's why you have to put the typename in.
The additional template is necessary whenever the nested name is the name of a template. If it was something else, then Data < ... could be a comparison.

like image 86
sbi Avatar answered Oct 24 '22 16:10

sbi


You need a typename and a template:

template <typename Provider>
inline void use()
{
    typedef typename Provider::template Data<int> D;
}
like image 34
James McNellis Avatar answered Oct 24 '22 16:10

James McNellis