gpt4 book ai didi

c++ - 使用 enable_if 选择性地添加结构成员

转载 作者:可可西里 更新时间:2023-11-01 17:37:19 26 4
gpt4 key购买 nike

给定这个模板:

template <class A>
struct Something {
... // members common to all template instantiations for all A types
SpecialType member; // but not this - I want this to be conditional...
}

...我想使用“enable_if”让 SpecialType 成员有条件地存在;也就是说,仅当模板以 A=SpecialCase1 或 SpecialCase2 类型实例化时。在所有其他情况下,我希望缺少 SpecialType 成员。

如果您想知道为什么,这是关于优化的——即不在结构中携带无用的负载。我是模板元编程的新手,但我知道我需要“enable_if”和两个“is_same” - 不确定具体如何......

编辑:使用通用 C++(即没有特定于 Boost 的)来完成它会是一个加号。

最佳答案

嗯:使用基类。

struct Empty {};

struct SpecialTypeCnt { SpecialType member; };

template <typename A>
struct Something: if_< /* cond */ , SpecialTypeCnt, Empty>::type {
};

其中 if_ 定义为:

template <typename, typename, typename E> struct if_ { typedef E type; };

template <typename T, typename E>
struct if_<std::true_type, T, E> { typedef T type; };

(你也可以专注于 bool 值)

当然,现在您需要适本地表达您的条件。


话虽如此,您可能不应该只使用一个struct。相反,您应该使用 class,它提供需要应用于 member 的操作。然后,您提供一个具有默认行为的 class Null 和一个具有特定于 member 的行为的 class SomeType

否则,您将在需要“可能”修改 member 的任何地方重写条件,这很快就会变得很烦人。

关于c++ - 使用 enable_if 选择性地添加结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10140231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com