C++ template compilation error: expected primary-expression before ‘>’ token
C++Visual C++GccBoostCompiler ErrorsC++ Problem Overview
This code compiles and works as expected (it throws at runtime, but never mind):
#include <iostream>
#include <boost/property_tree/ptree.hpp>
void foo(boost::property_tree::ptree &pt)
{
std::cout << pt.get<std::string>("path"); // <---
}
int main()
{
boost::property_tree::ptree pt;
foo(pt);
return 0;
}
But as soon as I add templates and change the foo
prototype into
template<class ptree>
void foo(ptree &pt)
I get an error in GCC:
test_ptree.cpp: In function ‘void foo(ptree&)’:
test_ptree.cpp:7: error: expected primary-expression before ‘>’ token
but no errors with MSVC++! The error is in the marked line <---
. And again, if I change the problem line into
--- std::cout << pt.get<std::string>("path"); // <---
+++ std::cout << pt.get("path", "default value");
the error disappears (the problem is in explicit <std::string>
).
[Boost.PropertyTree][1] requires Boost >= 1.41. Please help me to understand and fix this error.
See [Templates: template function not playing well with class’s template member function][2] — a similar popular question containing other good answers and explanations.
[1]: http://www.boost.org/doc/libs/1_44_0/doc/html/property_tree.html "Boost.PropertyTree" [2]: https://stackoverflow.com/questions/1682844/templates-template-function-not-playing-well-with-classs-template-member-functi
C++ Solutions
Solution 1 - C++
You need to do:
std::cout << pt.template get<std::string>("path");
Use template
in the same situation as typename
, except for template members instead of types.
(That is, since pt::get
is a template member dependent on a template parameter, you need to tell the compiler it's a template.)