【发布时间】:2016-11-27 21:06:00
【问题描述】:
我想在不更改其范围的情况下为类启用静态成员。 考虑以下抽象示例:
template<uint R, uint C>
class Foo
{
static Foo ID;
/* other members */
};
现在我想使用像这样的静态成员:
Foo<3, 3> foo = Foo<3, 3>::ID;
问题是ID字段只能在R == C时存在。
(Foo 实际上是 Matrix 和 ID 的标识,它只存在于方阵中)
所以我必须在满足条件时有条件地启用静态ID 成员。我目前的解决方案是这样的:
struct EmptyBase { };
template<uint R, uint C>
class _Foo_Square
{
static Foo<R, C> ID;
};
template<uint R, uint C>
class Foo : public std::conditional<R == C, _Foo_Square<R, C>, EmptyBase>::type
{
/* other members */
};
但现在我不能写Foo<3, 3>::ID 来访问它。我必须写_Foo_Square<3, 3>::ID。
不幸的是,我的应用程序的设计迫使Foo 类范围可以访问它。
如果它不是条件成员,我可以在 Foo 类中写 using _Foo_Square<3, 3>::ID;。
这个问题有解决办法吗?
【问题讨论】:
-
子类化似乎是个好主意。
-
"但是现在我不能写
Foo<3, 3>::ID来访问它。我必须写_Foo_Square<3, 3>::ID。" 从哪里访问它?正如您所展示的,唯一的“问题”是ID是私有的...... -
是的,如果您将其公开,您的代码就可以工作:coliru.stacked-crooked.com/a/0ceb5c6660a0fd8b
标签: c++ class templates c++11 conditional