使用enable_if可选择添加结构成员

tts*_*ras 8 c++ metaprogramming enable-if

鉴于此模板:

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...
}
Run Code Online (Sandbox Code Playgroud)

...我想使用"enable_if"使SpecialType成员有条件存在; 也就是说,只有在使用A = SpecialCase1或SpecialCase2类型实例化模板时.在所有其他情况下,我希望SpecialType成员丢失.

如果你想知道为什么,这是关于优化 - 即不在结构中携带无用的有效载荷.我是模板元编程的新手,但我知道我需要"enable_if"和两个"is_same" - 不确定究竟如何,但......

编辑:使用通用C++(即没有特定于Boost)是一个优点.

bob*_*bah 5

你不需要enable_if.专门针对特殊情况的结构,并保留其余的默认实现:

template <class A>
struct Something
{
  // your default implementation
};

template <>
struct Something<SpecialCase1>
{
  // your SpecialCase1 implementation
};

template <>
struct Something<SpecialCase2>
{
  // your SpecialCase2 implementation
};
Run Code Online (Sandbox Code Playgroud)


Mat*_* M. 5

好吧:使用基类.

struct Empty {};

struct SpecialTypeCnt { SpecialType member; };

template <typename A>
struct Something: if_< /* cond */ , SpecialTypeCnt, Empty>::type {
};
Run Code Online (Sandbox Code Playgroud)

在哪里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; };
Run Code Online (Sandbox Code Playgroud)

(你也可以专门研究一个布尔值)

当然,你需要正确表达你的状况.


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

否则你将在任何你需要"修改"的地方重写这个条件member,而且它很快就会变得烦人.

  • `if_`通常称为`std :: conditional`. (3认同)