C++ 模板编译错误:“>"标记之前的预期主表达式
此代码编译并按预期工作(它在运行时抛出,但没关系):
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;
}
但是一旦我添加模板并将 foo
原型更改为
But as soon as I add templates and change the foo
prototype into
template<class ptree>
void foo(ptree &pt)
我在 GCC 中遇到错误:
I get an error in GCC:
test_ptree.cpp: In function ‘void foo(ptree&)’:
test_ptree.cpp:7: error: expected primary-expression before ‘>’ token
但 MSVC++ 没有错误!错误在标记的行 <---
中.再一次,如果我将问题行更改为
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 需要 Boost >= 1.41.请帮助我理解并修复此错误.
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.
推荐答案
你需要做的:
std::cout << pt.template get<std::string>("path");
在与 typename
相同的情况下使用 template
,除了模板成员而不是类型.
Use template
in the same situation as typename
, except for template members instead of types.
(也就是说,由于 pt::get
是模板成员依赖模板参数,你需要告诉编译器它是一个模板.)
(That is, since pt::get
is a template member dependent on a template parameter, you need to tell the compiler it's a template.)
相关文章