如何在带有 gcc 4.8 且没有 C++11 标志的情况下使用 c++ 中的正则表达式?
How to work with regular expressions in c++ with gcc 4.8 and without C++11 flag?
我最近发现 gcc 4.8 中的 regex 支持不完整,在 gcc 4.9 中真正实现了(参见 Is gcc 4.8 or earlier buggy about regular expressions?)。
因此,为了在我的 C++ 程序中使用正则表达式,我按照此说明将我的 gcc 更新为 4.9 (https://askubuntu.com/questions/466651/how-do-i-use-the-latest-gcc-4-9-on-ubuntu-14-04)。
现在,当我尝试编译我的程序时,它说为了 #include <regex>
我必须指定编译器标志 -std=c++11
,我这样做了,现在我面临新的编译我以前没有遇到的问题 (‘constexpr’ needed for in-class initialization of static data member
)。
鉴于此,我认为目前最好坚持使用 gcc 4.8,并且不要在编译时指定 gnu++11 标志。回到方块 1.
那么,如果我不想切换到 gcc 4.9 也不想用 c++11 标记编译器,我可以在 c++ 中使用正则表达式吗?还有别的办法吗?
谢谢!
PS:实际上是c++11 flag导致编译问题,而不是gcc的版本,对吧?
您可以安装 PCRE 库并使用它代替 C++11 标准正则表达式。 PCRE 实际上是作为 C library/interface 而不是 C++ 设计的,但是编写一些简单的包装器 类 或仅将其用作 C 库非常容易。
该错误很可能意味着您依赖 non-standard GCC extension 来初始化非整数类型,如下所示:
struct X {
static const double d = 3.14;
};
这在 C++98 中无效,但 GCC 支持。
C++11 标准增加了对初始化非整数类型的支持,但您需要使用 constexpr
例如
struct X {
static constexpr double d = 3.14;
};
当您使用 -std=c++11
或 -std=gnu++11
编译时,不再支持旧的 GCC 特定扩展。你必须使用标准的 C++11 方式,使用 constexpr
.
因此您可以通过将其更改为 constexpr
或使其与 GCC 的 C++98 扩展以及 C++11 兼容来轻松解决错误:
struct X {
#if __cplusplus > 199711L
static constexpr double d = 3.14;
#else
// this is non-standard but allowed by GCC in C++98 mode
static const double d = 3.14;
#endif
};
这将允许您使用 -std=c++11
进行编译,因此您可以使用 GCC 4.9 的工作 std::regex
。
我最近发现 gcc 4.8 中的 regex 支持不完整,在 gcc 4.9 中真正实现了(参见 Is gcc 4.8 or earlier buggy about regular expressions?)。
因此,为了在我的 C++ 程序中使用正则表达式,我按照此说明将我的 gcc 更新为 4.9 (https://askubuntu.com/questions/466651/how-do-i-use-the-latest-gcc-4-9-on-ubuntu-14-04)。
现在,当我尝试编译我的程序时,它说为了 #include <regex>
我必须指定编译器标志 -std=c++11
,我这样做了,现在我面临新的编译我以前没有遇到的问题 (‘constexpr’ needed for in-class initialization of static data member
)。
鉴于此,我认为目前最好坚持使用 gcc 4.8,并且不要在编译时指定 gnu++11 标志。回到方块 1.
那么,如果我不想切换到 gcc 4.9 也不想用 c++11 标记编译器,我可以在 c++ 中使用正则表达式吗?还有别的办法吗?
谢谢!
PS:实际上是c++11 flag导致编译问题,而不是gcc的版本,对吧?
您可以安装 PCRE 库并使用它代替 C++11 标准正则表达式。 PCRE 实际上是作为 C library/interface 而不是 C++ 设计的,但是编写一些简单的包装器 类 或仅将其用作 C 库非常容易。
该错误很可能意味着您依赖 non-standard GCC extension 来初始化非整数类型,如下所示:
struct X {
static const double d = 3.14;
};
这在 C++98 中无效,但 GCC 支持。
C++11 标准增加了对初始化非整数类型的支持,但您需要使用 constexpr
例如
struct X {
static constexpr double d = 3.14;
};
当您使用 -std=c++11
或 -std=gnu++11
编译时,不再支持旧的 GCC 特定扩展。你必须使用标准的 C++11 方式,使用 constexpr
.
因此您可以通过将其更改为 constexpr
或使其与 GCC 的 C++98 扩展以及 C++11 兼容来轻松解决错误:
struct X {
#if __cplusplus > 199711L
static constexpr double d = 3.14;
#else
// this is non-standard but allowed by GCC in C++98 mode
static const double d = 3.14;
#endif
};
这将允许您使用 -std=c++11
进行编译,因此您可以使用 GCC 4.9 的工作 std::regex
。