问题 根据模板参数声明成员与否


是否可以根据模板条件声明成员变量而不使用虚拟空类型?

例:

struct empty{};
struct real_type{};

template<bool condition>
struct foo
{
    typename std::conditional<condition, real_type, empty>::type _member;
};

968
2018-05-21 14:58


起源



答案:


您可以从具有特化的模板派生:

struct real_type { };

template<bool c>
struct foo_base { };

template<>
struct foo_base<true>
{
    real_type _member;
};

template<bool condition>
struct foo : foo_base<condition>
{
};

作为一个小测试:

int main()
{
    foo<true> t;
    t._member.x = 42; // OK

    foo<false> f;
    f._member.x = 42; // ERROR! No _member exists
}

12
2018-05-21 15:01



@MikeSeymour:对,剩下:)谢谢,编辑 - Andy Prowl
大!这样,当条件为假时,我的类中不会有“空”结构 - Felics
@Felics:是的,这是对的 - Andy Prowl
@Felics你正在交易另一种空。不知道为什么你会关心一个空的 struct 成员变量开始,但无论如何...... - Nik Bougalis
@NikBougalis不是真的。派生空结构时可能会被优化为非空,但成员必须具有不同的地址且不能为“空”。最好不要有一个污染名称空间的成员而不是一个虚拟成员。这样做是为了启用/禁用某些功能,并考虑到我有很多功能,我可以通过设置一些bool模板参数而不是编写组合数量的类来获得任何组合 - Felics


答案:


您可以从具有特化的模板派生:

struct real_type { };

template<bool c>
struct foo_base { };

template<>
struct foo_base<true>
{
    real_type _member;
};

template<bool condition>
struct foo : foo_base<condition>
{
};

作为一个小测试:

int main()
{
    foo<true> t;
    t._member.x = 42; // OK

    foo<false> f;
    f._member.x = 42; // ERROR! No _member exists
}

12
2018-05-21 15:01



@MikeSeymour:对,剩下:)谢谢,编辑 - Andy Prowl
大!这样,当条件为假时,我的类中不会有“空”结构 - Felics
@Felics:是的,这是对的 - Andy Prowl
@Felics你正在交易另一种空。不知道为什么你会关心一个空的 struct 成员变量开始,但无论如何...... - Nik Bougalis
@NikBougalis不是真的。派生空结构时可能会被优化为非空,但成员必须具有不同的地址且不能为“空”。最好不要有一个污染名称空间的成员而不是一个虚拟成员。这样做是为了启用/禁用某些功能,并考虑到我有很多功能,我可以通过设置一些bool模板参数而不是编写组合数量的类来获得任何组合 - Felics


是否可以根据模板条件声明成员变量而不使用虚拟空类型?

我相信你也可以 专攻   推导。这两个测试都没问题 -std=c++03 和 -std=c++11

template<bool condition>
struct foo;

template<>
struct foo<true>
{
    real_type _member;
};

template<>
struct foo<false>
{
};

如果C ++委员会给了我们想要/需要的东西,那肯定会很好:

template<bool condition>
struct foo
{
#if (condition == true)
    real_type _member;
#endif
};

0
2018-04-13 05:42