テストにのみ使用されるクラスのビッグデータメンバーがあります。
template <bool testing>
class foo {
int testbuf[1000];
}
どうすればそうできますか?の場合のみ、 ?testing
をtrue
含めます。testbuf[]
専門:
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
ください。
ifdefのものを使用できます
#define DEBUG_MODE
class Foo{
#ifdef DEBUG_MODE
int testbuf[1000];
#else
int testbuf[10];
#endif
}
template <bool testing>
class foo {
}
と
template <>
class foo <true>{
int testbuf[1000];
}
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.
});
}
しかし、それは私だけです。