0

我有一个类的大数据成员,仅用于测试:

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

我怎样才能做到这一点?仅当testingtrue,包括testbuf[]

4

4 回答 4

3

Specialize:

template <bool> class foo { };

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

Update: To clarify some points raised in the comments: You would write one such "testing" template per individual item that you want to specialize, so that there's no code duplication. Imagine your real class template is actually bar:

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

    Widget<Testing> widget;     // specializable member

    Gadget          gadget;     // unconditional member
};

You can also use composition rather than inheritance; whichever fits best. If you go with inheritance, make sure to spell out this->testbuf.

于 2012-11-09T22:27:48.577 回答
1

you can use ifdef stuff

#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 {
}

and

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

我会假设这testing不仅仅是用来保持那个buff。

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> {
  // ...
};

更进一步,您可以在 foobuf 中包含一个 dotest 函数,其工作原理如下:

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 回答