我有一个带有模板参数的结构,Stream
。在该结构中,有一个具有自己的模板参数 Type
的函数。
如果我尝试强制生成并调用该函数的特定实例,它可以正常工作,如果我处于已知结构的确切类型的上下文中。如果没有,我会收到编译错误。这感觉就像我缺少 typename
的情况,但没有嵌套类型。我怀疑我错过了一些基本的东西,但我已经盯着这段代码这么久了,我看到的都是红发女郎,坦白说,编写使用模板的代码从来都不是我的强项。
以下是我能想到的最简单的示例来说明该问题。
#include <iostream>
template<typename Stream>
struct Printer {
Stream& str;
Printer(Stream& str_) : str(str_) { }
template<typename Type>
Stream& Exec(const Type& t) {
return str << t << std::endl;
}
};
template<typename Stream, typename Type>
void Test1(Stream& str, const Type& t) {
Printer<Stream> out = Printer<Stream>(str);
/****** vvv This is the line the compiler doesn't like vvv ******/
out.Exec<bool>(t);
/****** ^^^ That is the line the compiler doesn't like ^^^ ******/
}
template<typename Type>
void Test2(const Type& t) {
Printer<std::ostream> out = Printer<std::ostream>(std::cout);
out.Exec<bool>(t);
}
template<typename Stream, typename Type>
void Test3(Stream& str, const Type& t) {
Printer<Stream> out = Printer<Stream>(str);
out.Exec(t);
}
int main() {
Test2(5);
Test3(std::cout, 5);
return 0;
}
正如所写,gcc-4.4 给出以下内容:
test.cpp: In function 'void Test1(Stream&, const Type&)':
test.cpp:22: error: expected primary-expression before 'bool'
test.cpp:22: error: expected ';' before 'bool'
Test2
和 Test3
都可以干净地编译,如果我注释掉 Test1
程序就会执行,并且我会得到“1 5”预计。所以看起来我想做的事情没有任何问题,但我在实现过程中搞砸了一些事情。
如果有人能够阐明我所忽略的内容,我将不胜感激。
最佳答案
你需要告诉编译器依赖名称 Printer<Stream>::Exec
是一个模板:
out.template Exec<bool>(t);
与 typename
原理相同,只是在这种情况下有问题的名称不是类型,而是模板。
关于c++ - 显式实例化泛型结构的泛型成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2541289/