Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?
Here's the code:
template<typename T>
class base
{
public:
virtual ~base();
template<typename F>
void foo()
{
std::cout << "base::foo<F>()" << std::endl;
}
};
template<typename T>
class derived : public base<T>
{
public:
void bar()
{
this->foo<int>(); // Compile error
}
};
And, when running:
derived<bool> d;
d.bar();
I get the following errors:
error: expected primary-expression before ‘int’
error: expected ‘;’ before ‘int’
I'm aware of non-dependent names and 2-phase look-ups. But, when the function itself is a template function (foo<>()
function in my code), I tried all workarounds only to fail.
A template allows us to create a family of classes or family of functions to handle different data types. Template classes and functions eliminate the code duplication of different data types and thus makes the development easier and faster. Multiple parameters can be used in both class and function template.
You may overload a function template either by a non-template function or by another function template. The function call f(1, 2) could match the argument types of both the template function and the non-template function.
For normal code, you would use a class template when you want to create a class that is parameterised by a type, and a function template when you want to create a function that can operate on many different types.
Function templates. Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.
foo
is a dependent name, so the first-phase lookup assumes that it's a variable unless you use the typename
or template
keywords to specify otherwise. In this case, you want:
this->template foo<int>();
See this question if you want all the gory details.
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