C++ 使用较新编译器的功能生成代码以供较旧编译器使用

C++ Using features of a newer compiler to generate code for use by an older compiler

我一直在研究 "newer" C++ 标准(C++11 和 C++14)的一些特性,这让我开始思考一些事情。我目前正在为我的项目使用 VC++2008 编译器(出于各种原因),这意味着我可以访问的最新标准是 C++03,加上 TR1。 TR1 中有一些不错的东西,但 C++11 和 C++14 中的一些特性如果有的话就更好了。

我的问题是:是否有任何方法可以使用较新的编译器(例如 MSVC2012 或 2013)构建一些代码,以使用较新的 C++11 和C++14 功能,然后 link 进入我的项目,即 运行 '08 编译器?

我唯一能想到的是在我的 '08 编译器项目包含的 header 中必须具有 C++11 或 C++14 功能的任何地方.然而,只要所有东西 "new" 都隐藏在我的界面后面,这不应该有效吗?

是的,但它会变得丑陋..因为 ABI 不兼容,你必须降低到“extern "C" {}”ABIness。

这意味着您根本无法传递 C++ 对象.. 就像我说的,很痛苦。这也意味着它必须是一个 DLL,因为您将无法 link 在带有另一个 ABI 的静态库中。

是否值得在 C 语言中封装一个 DLL 取决于您 API 是否只是为了使用一些新功能,不过我还是建议升级整个项目。

我差点忘了,你可能也不能 link 导入库,所以你必须有一些使用 LoadLibraryGetProcAddress 和 [=13 的代码=](我有没有提到这是 ugly/painful?)。

不幸的是,MSVC 无法实现您想要执行的操作。他们故意破坏与每个主要版本的二进制兼容性,如 MSDN documentation:

中所述

To enable new optimizations and debugging checks, the Visual Studio implementation of the C++ Standard Library intentionally breaks binary compatibility from one version to the next. Therefore, when the C++ Standard Library is used, object files and static libraries that are compiled by using different versions can't be mixed in one binary (EXE or DLL), and C++ Standard Library objects can't be passed between binaries that are compiled by using different versions. Such mixing emits linker errors about _MSC_VER mismatches. (_MSC_VER is the macro that contains the compiler's major version—for example, 1800 for Visual C++ in Visual Studio 2013.) This check cannot detect DLL mixing, and cannot detect mixing that involves Visual C++ 2008 or earlier.

然后您的选择是只传递 POD 类型,或实现 COM 接口以在使用不同版本的 VC 编译器编译的 DLL 之间进行互操作,这两种方法都不是特别可口。

我的建议是,如果您必须为某些遗留应用程序坚持使用 VS2008,请接受它并处理它支持的功能集(至少您有 TR1)。对于较新的项目,请尝试说服您的团队使用较新版本的 VC.