嵌套模板
问题描述:
我有一个奇怪的问题与C++模板,我不明白为什么下面的代码不工作:嵌套模板
#include <iostream>
template <typename A, typename B>
class TypePair {
public:
typedef A First;
typedef B Second;
};
template <typename P>
class Foo {
public:
Foo(P::First f, P::Second) {
std::cout
<< "first = " << f << std::endl
<< "second = " << s << std::endl;
}
};
int main(int argc, char **argv) {
Foo<TypePair<int, double> > foo(42, 23.0);
return 0;
}
的代码产生以下错误:
$ g++ templates.cpp -o templates
templates.cpp:14: error: expected ‘)’ before ‘f’
templates.cpp: In function ‘int main(int, char**)’:
templates.cpp:23: error: no matching function for call to ‘Foo<TypePair<int, double> >::Foo(int, double)’
templates.cpp:12: note: candidates are: Foo<TypePair<int, double> >::Foo()
templates.cpp:12: note: Foo<TypePair<int, double> >::Foo(const Foo<TypePair<int, double> >&)
对我来说代码看起来非常好,但g ++显然有自己的观点^^有什么想法?
塞巴斯蒂安
答
使用
Foo(typename P::First f, typename P::Second s)
因为P是一个模板参数,P ::第一和P ::二是相关的名字,所以你必须明确指定他们typenames,不为例如,静态数据成员。 See this了解详情
非常感谢您的快速回复!它完美地解决了我的问题。 – Sebastian 2011-04-01 09:31:48
+1一个不错的链接,谢谢。 – 2011-04-01 09:33:17