声明成员与否取决于模板形参

Declaring member or not depending on template parameter

本文关键字:形参 取决于 成员 声明      更新时间:2023-10-16

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

的例子:

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

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

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
}

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

我相信你也可以专门化而不需要派生。这在-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
};