是否可以根据模板条件而不使用虚假空类型来声明或不声明成员变量?
例如:
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
};
struct
成员变量,但无论如何... - Nik Bougalistemplate<typename T, identifier X, bool b> struct maybe_member {}; template<typename T, identifier X> struct maybe_member<T,X,true> {T X;};
。我们能做的最好的办法是使用类型标签,这会引入一种奇怪的语法和“成员”访问的样板代码。 - Yakk - Adam Nevraumont