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.
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.
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.
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? 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.
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.
You need a typename
and a template
:
template <typename Provider>
inline void use()
{
typedef typename Provider::template Data<int> D;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With