我想在不改变类作用域的情况下为类启用一个静态成员。考虑以下抽象示例:
template<uint R, uint C>
class Foo
{
static Foo ID;
/* other members */
};
现在我想使用静态成员,如:
Foo<3, 3> foo = Foo<3, 3>::ID;
问题是CCD_ 1字段只能在CCD_
(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类中编写ID
0。
这个问题有解决办法吗?
答案是修复代码中的一些错误,和/或切换到更好的编译器。
在添加了一个适当的前向声明,并将静态类成员声明为public
之后,以下内容的编译与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;
}
我能想到的最简单的版本:
typedef unsigned int uint;
template<uint R, uint C>
class Foo
{
//no ID here
};
template<uint R>
class Foo<R,R>
{
public:
static constexpr Foo ID = Foo();
};
int main()
{
Foo<3,3> foo1 = Foo<3,3>::ID; //ok
Foo<3,4> foo2 = Foo<3,4>::ID; //error
}
专门化基类Bar
,您可以执行类似的操作
#include <iostream>
template <std::size_t, std::size_t>
struct Foo;
template <std::size_t, std::size_t>
struct Bar
{ };
template <std::size_t N>
struct Bar<N, N>
{ static Foo<N, N> ID; };
template <std::size_t R, std::size_t C>
struct Foo : Bar<R, C>
{
// other members
};
int main ()
{
Foo<3, 3> foo = Foo<3, 3>::ID;
return 0;
}