0

テストにのみ使用されるクラスのビッグデータメンバーがあります。

template <bool testing>
class foo {
  int testbuf[1000];
}

どうすればそうできますか?の場合のみ、 ?testingtrue含めます。testbuf[]

4

4 に答える 4

3

専門:

template <bool> class foo { };

template <> class foo<true>
{
    // everything needed for testing
};

更新:コメントで提起されたいくつかのポイントを明確にするために:コードの重複がないように、専門にしたい個々のアイテムごとに1つのそのような「テスト」テンプレートを作成します。実際のクラステンプレートが実際にあると想像してくださいbar

template <bool Testing>
class bar
: private foo<Testing>          // specializable base
{
    // common stuff

    Widget<Testing> widget;     // specializable member

    Gadget          gadget;     // unconditional member
};

継承ではなく構成を使用することもできます。最適な方。継承を使用する場合は、必ずスペルアウトしてthis->testbufください。

于 2012-11-09T22:27:48.577 に答える
1

ifdefのものを使用できます

#define DEBUG_MODE

class Foo{
  #ifdef DEBUG_MODE
      int testbuf[1000];
  #else
      int testbuf[10];
  #endif
}
于 2012-11-09T22:28:29.307 に答える
0
template <bool testing>
class foo {
}

template <>
class foo <true>{
  int testbuf[1000];
}
于 2012-11-09T22:28:15.097 に答える
0

testingそのバフを保持するためだけに使用されているわけではないと思います。

template <bool testing>
struct foobuf
{};
template <>
struct foobuf<true>
{
  enum {testbuf_size = 1000};
  int testbuf[testbuf_size];
  foobuf() { std::fill_n( &testbuff[0], testbuf_size, int() ); }
};

template <bool testing>
class foo : public foobuf<testing> {
  // ...
};

もう少し先に進むと、次のように機能する dotest 関数を foobuf に含めることができます。

template<bool>
struct foobuf
{
  template<typename Func>
  void doTest( Func const& unused );
};
template<>
struct foobuf<true>
{
  enum {testbuf_size = 1000};
  int testbuf[testbuf_size];
  foobuf() { std::fill_n( &testbuf[0], testbuf_size, int() ); }
  template<typename Func>
  void doTest( Func const& f )
  {
    f( testbuf, testbuf_size );
  }
};

foo 内で次のように使用します。

void foo::some_function(...)
{
  // some code
  doTest( [&]( int* buf, size_t length )
  {
    // the code in here only runs if we test was true in foo
    // and if so, it has access to the test buff via the buf* parameter
    // oh, and it will be almost certainly inlined if test was true in foo
    // and thrown away and never created if it was false.
  });
}

しかし、それは私だけです。

于 2012-11-09T22:40:27.763 に答える