问题描述
免责声明:以下问题可能很容易,我可能会震惊看到第一个答案。此外,我想为任何重复的问题道歉 - 句法问题并不总是很容易识别语言解释,因此搜索他们不是那么容易...
Disclaimer: The following question probably is so easy that I might be shocked seeing the first answer. Furthermore, I want to apologize for any duplicate questions - syntactic problems are not always easy to identify be verbal explanation and thus searching for them is not as easy...
但是足够的。我有一个两个模板化的类,其中一个有模板成员函数,其他类试图调用该函数。一个最小的错误产生示例如下所示:
But enough of that. I have a two templated classes, one of those has a templated member function, the other class attempts to call that function. A minimal, error producing example is shown below:
#include <iostream>
template <typename T>
class Foo {
public:
Foo() {
}
template <typename outtype>
inline outtype bar(int i, int j, int k = 1) {
return k;
}
};
template <typename T>
class Wrapper {
public:
Wrapper() {
}
double returnValue() {
Foo<T> obj;
return obj.bar<double>(1,2); // This line is faulty.
}
};
int main() {
Wrapper<char> wr;
double test = wr.returnValue();
std::cout << test << std::endl;
return 0;
}
在编译时,这会导致
At compile time, this results in
expected primary-expression before 'double'
expected ';' before 'double'
expected unqualified-id before '>' token
其中所有错误消息都指向代码中标记的链接。
where all error messages are directed at the linke marked in the code.
我已经谢谢你的想法,不管它们有多明显。
I allready thank you for your ideas, no matter how obvious they are.
推荐答案
obj.bar<double>(1,2); // This line is faulty.
此处需要模板
关键字 obj
是 Foo
类型的实例,其中取决于模板参数 T
,因此上面应该写成:
The template
keyword is required here, as obj
is an instance of a type Foo<T>
which depends on the template parameter T
, and so the above should be written as:
obj.template bar<double>(1,2); //This line is corrected :-)
阅读@ Johannes的答案这里详细解释:
Read @Johannes's answer here for detail explanation:
- Where and why do I have to put "template" and "typename" on dependent names?
这篇关于调用模板类中的模板函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!