问题
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.
回答1:
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.
回答2:
You should do it like this :
template<typename T>
class derived : public base<T>
{
public:
void bar()
{
base<T>::template foo<int>();
}
};
Here is full compilable example :
#include <iostream>
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()
{
base<T>::template foo<int>(); // Compile error
}
};
int main()
{
derived< int > a;
a.bar();
}
来源:https://stackoverflow.com/questions/9289859/calling-template-function-of-template-base-class