【问题标题】:Enabling a static member conditionally without changing the member scope有条件地启用静态成员而不更改成员范围
【发布时间】: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&lt;3, 3&gt;::ID 来访问它。我必须写_Foo_Square&lt;3, 3&gt;::ID。

不幸的是,我的应用程序的设计迫使Foo 类范围可以访问它。 如果它不是条件成员,我可以在 Foo 类中写 using _Foo_Square&lt;3, 3&gt;::ID;。

这个问题有解决办法吗?

【问题讨论】:

  • 子类化似乎是个好主意。
  • "但是现在我不能写Foo&lt;3, 3&gt;::ID 来访问它。我必须写_Foo_Square&lt;3, 3&gt;::ID。" 从哪里访问它?正如您所展示的,唯一的“问题”是ID 是私有的......
  • 是的,如果您将其公开,您的代码就可以工作:coliru.stacked-crooked.com/a/0ceb5c6660a0fd8b

标签: c++ class templates c++11 conditional


【解决方案1】:

答案是修复代码中的一些错误,和/或切换到更好的编译器。

在添加正确的前向声明并将静态类成员声明为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;
}

【讨论】:

  • 问题是,和往常一样,我忘记将public: 放在分解版本中。我已经在我的代码中找到了它,但它仍然无法用我的 gcc 6.1.1 编译。它只是说没有在这个范围内声明
  • 为我工作。所示代码使用 gcc 6.1.1 编译
  • 是的,我开始相信我的代码中还有其他东西可以防止这种情况发生。实际上我有两层继承,但我认为这不是问题。
  • 这就是为什么问题需要包含minimal reproducible example。否则,你就是在浪费大家的时间。
  • @bricklore - 我确认:将 void foobar() 更改为 int main(),代码使用 g++ 4.9.2 和 clang++ 3.5 编译
【解决方案2】:

专门化一个基类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;
 }

【讨论】:

    【解决方案3】:

    我能想到的最简单的版本:

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-25
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 2015-09-11
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 2012-04-10
      相关资源
      最近更新 更多