gpt4 book ai didi

c++ - 调用模板基类的模板函数

转载 作者:IT老高 更新时间:2023-10-28 22:33:01 28 4
gpt4 key购买 nike

Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?

代码如下:

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
}
};

并且,在运行时:

derived<bool> d;
d.bar();

我收到以下错误:

error: expected primary-expression before ‘int’
error: expected ‘;’ before ‘int’

我知道non-dependent names and 2-phase look-ups .但是,当函数本身是模板函数(我的代码中的 foo<>() 函数)时,我尝试了所有变通方法都失败了。

最佳答案

foo 是一个依赖名称,因此第一阶段查找假定它是一个变量,除非您使用 typenametemplate 关键字另有说明。在这种情况下,您需要:

this->template foo<int>();

this question如果你想要所有血淋淋的细节。

关于c++ - 调用模板基类的模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9289859/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com