I have an odd problem with C++ templates and I don’t understand why the following code is not working:
#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;
}
The code produces the following errors:
$ 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> >&)
For me the code this looks totally fine, but g++ obviously has its own opinion ^^ Any ideas?
Sebastian
Use
Since P is a template parameter, P::First and P::Second are dependent names, so you have to explicitly specify they are typenames, not, for example, static data members. See this for details