C++ template compilation error: expected primary-expression before ‘>’ token
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.)
Andrew T
Sorry, English is not my native language, but I try to use it properly.
Updated on July 09, 2022Comments
-
Andrew T almost 2 years
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 intotemplate<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 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 — a similar popular question containing other good answers and explanations.
-
Chance over 12 yearsNice. Do you have a specific resource you use for template usage? I ask out of curiosity. None of my books seemed to address this issue.
-
GManNickG over 12 years@Chance: I don't, sadly, though you might find one off this list, namely C++ Templates, The Complete Guide.
-
HelloGoodbye over 8 yearsWhy do you need to tell the compiler it's a template? Shouldn't the compiler be able to figure that out by itself?
-
GManNickG over 8 years@HelloGoodbye: I don't remember if it's theoretically possible in C++ for the compiler to always deduce it correctly, probably not. The problem is that without
template
, it could be parsed as(pt.get) < std::string > ("path");
, that is comparisons. In this case, comparisons for type names isn't possible so it could figure out, but in general how would you parsept.val < 5 > (10)
? Addingtemplate
tells the compiler directly "this is a function call". -
HelloGoodbye over 8 yearsAh, okay, so it is the old incompatibility problem with comparison operators and template notation again... :P Well, that makes sense. I guess the D programming language has the upper hand here with its
(...)
template syntax instead of C++'<...>
syntax :)