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
Foo(typename P::First f, typename P::Second s)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With