C++ 中多类型函数变体的 switch 案例数限制

问题描述 投票:0回答:1

我编写了一个类:

template<unsigned int N>
class WrappedUInt {
    unsigned int m_value;
public:
// Many methods to imitate the unsigned integer type
// This class works as a interface (except for `N==0 || N==1`)
};

template<> class WrappedUInt<0> : public std::false_type {};
template<> class WrappedUInt<1> : public std::true_type {};

然后我为应用程序定义了一个变体类型:

using wuint_64_variant = std::variant<
    WrappedUInt<0>,WrappedUInt<1>,WrappedUInt<2>,WrappedUInt<3>,WrappedUInt<4>,WrappedUInt<5>,
    // to complete this large list with step 1
    WrappeUInt<60>,WrappeUInt<61>,WrappeUInt<62>,WrappeUInt<63>
>;

现在我需要这个变体类型的函数。我使用 switch/case 语句来处理这个。它非常适合声明中的 2、3、4、...、63 个不同的案例。

我读到g++编译器将案例数限制在200个,clang++、MSVC和Intel编译器限制在256个,标准推荐最低为16384个。

但是 gcc 超过 63 个 case 加上 default case 就失败了,错误是'File too big',why?

另一个问题是我可以增加 switch 语句中允许的案例数吗?

c++ switch-statement
1个回答
-1
投票

'File too big'错误与目标文件中的节数限制有关,该限制通常由操作系统设置。当你使用带有大量 case 的 switch 语句时,编译器会生成一个跳转表,它是指向每个 case 的代码的指针数组。如果案例数量太多,跳转表的大小可能会超过部分数量的限制,从而导致错误。

要解决此问题,您可以尝试使用不同的方法(例如哈希表或二叉搜索树)来实现 switch 语句。或者,您可以将 switch 语句拆分为多个更小的 switch 语句,或者改用 if-else 链。

关于你的第二个问题,switch语句允许的case个数是由编译器和平台决定的,没有标准的增加方式。但是,如前所述,您可以使用其他方法来实现相同的逻辑,而无需依赖大型 switch 语句。

© www.soinside.com 2019 - 2024. All rights reserved.