包含 boost/optional.hpp 时出现 C2143 语法错误

C2143 syntax error when including boost/optional.hpp

我遇到了无法理解的 compile-time 错误。我尝试在我的代码中使用 boost::optional,一旦我包含 boost/optional.hpp,我就无法再构建我的项目。如果我注释掉这个 include 语句,它就起作用了。我什至还没有在我的代码中实际使用 boost::optional,只有 class header 中的 include 语句(请参阅下面的完整 header)。编译器错误是 C2143 syntax error: missing ',' before '<',它发生在另一个 Boost header boost/utility/compare_pointees.hpp 中(参见下面的 GitHub link)。我也已经在同一个项目中成功地使用了来自 Boost 的其他东西,比如 boost::filesystem::path,所以我的 Boost 发行版应该没有问题。

这是我的环境:Microsoft Visual Studio Professional 2015 Version 14.0.25431.01 Update 3boost 1.62.0。我也使用 third-party 库 C++ REST SDK,其他都是 C++ 标准库的东西。

我的 header 看起来像这样。我想添加一个 boost::optional<size_t> 作为 return 类型的新方法。

#pragma once

#include <boost/optional.hpp>   // <==== ERROR

// C++ REST SDK
#define _TURN_OFF_PLATFORM_STRING
#include <cpprest/http_listener.h>
#include <cpprest/http_msg.h>

namespace SANDBOX::REST
{
   class HttpGetHandler
   {
   public:
       virtual void HandleHttpGetRequest(web::http::http_request request) = 0;
   };
}

报编译错误的地方在Boost header boost/utility/compare_pointees.hpp, line 36. 你可以在GitHub 下查看这个文件的完整内容 https://github.com/boostorg/utility/blob/boost-1.62.0/include/boost/utility/compare_pointees.hpp

编译器输出仅显示以下消息:

1>D:\dev\lib\boost_1_62_0\boost/utility/compare_pointees.hpp(36): error C2143: syntax error: missing ',' before '<'
1>  D:\dev\lib\boost_1_62_0\boost/utility/compare_pointees.hpp(40): note: see reference to class template instantiation 'boost::equal_pointees_t<OptionalPointee>' being compiled
1>D:\dev\lib\boost_1_62_0\boost/utility/compare_pointees.hpp(59): error C2143: syntax error: missing ',' before '<'
1>  D:\dev\lib\boost_1_62_0\boost/utility/compare_pointees.hpp(63): note: see reference to class template instantiation 'boost::less_pointees_t<OptionalPointee>' being compiled
========== Build: 0 succeeded, 1 failed, 2 up-to-date, 0 skipped ==========

肯定不是Boost库的问题。但是我怎么才能弄清楚,我的 classes 或项目设置有什么问题?

P.S。即使我在我的项目中使用这些最原始的 header 和源文件,我也可以重现该行为:

Header 文件 Test.h:

#pragma once

#include <boost/optional.hpp>

源文件Test.cpp:

#include "../include/Test.h"

由于 jv_. I turned on compiler switch /std:c++latest in my project settings to be able to use C++17 nested namespace definition 功能的宝贵提示,我可以找出原因。激活此开关会删除一些已弃用的语言功能,特别是 std::binary_function,它仍在当前的 Boost 发行版 (1.62.0) 中使用,因此会产生编译器错误。最后,我决定删除开关 /std:c++latest(并使用普通方式声明我的名称空间),这解决了问题。谢谢大家的帮助。

问题已在 boost 1.63.0 中修复。它不再使用在 C++17 中删除的 std::binary_function

在我的例子中,我在 Force 包含文件(C++->Advanced)中有一个#define new DEBUG_NEW。 我通过在 boost #include 之后添加 #undef new 来修复它,然后在之后添加 #define new DEBUG_NEW。