问题描述
我想为类启用静态成员,而不更改其范围。
考虑下面的抽象例子:
I want to enable a static member for a class without changing its scope.Consider the following abstracted example:
template<uint R, uint C>
class Foo
{
static Foo ID;
/* other members */
};
现在我想使用静态成员:
Now I want to use the static member like:
Foo<3, 3> foo = Foo<3, 3>::ID;
问题是 ID
仅当 R == C
时才存在。
( Foo
实际上是 Matrix
和 ID
其唯一的方形矩阵存在)
The problem is that the ID
field can only exist when R == C
.
(Foo
is actually a Matrix
and ID
its identity which only exists for square matrices)
我必须有条件地启用静态 ID
成员时满足条件。我现在的解决方案是这样:
So I have to conditionally enable the static ID
member when the condition is met. My current solution is something like this:
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& / code>来访问它。我必须写
_Foo_Square< 3,3> :: ID
。
不幸的是,我的应用程序的设计迫使它可以通过 Foo
类范围访问。
如果不是条件成员,我可以在Foo类中使用_Foo_Square< 3,3> :: ID; 来写。
Unfortunately the design of my application forces it to be accessible by the Foo
class scope.If it wasn't a conditional member I could write using _Foo_Square<3, 3>::ID;
in the Foo class.
这个问题有没有解决方案?
Is there a solution to this problem?
推荐答案
添加正确的前向声明并声明静态类成员为 public
,以下编译没有gcc 6.1.1的问题:
After adding a proper forward declaration, and declaring the static class member as public
, the following compiles without issues with gcc 6.1.1:
#include <utility>
struct EmptyBase { };
template<int R, int C> class Foo;
template<int R, int C>
class _Foo_Square
{
public:
static Foo<R, C> ID;
};
template<int R, int C>
class Foo : public std::conditional<R == C, _Foo_Square<R, C>, EmptyBase>::type
{
/* other members */
};
void foobar()
{
Foo<3, 3> a=Foo<3, 3>::ID;
}
这篇关于有条件地启用静态成员,而不更改成员作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!