1

ブーストを使用しているため、そのライブラリを使用しても問題ありません。

しかし、単一のデータ型に特化するのではなく、データ型のクラス全体に適切な特殊化を提供する一連のテンプレートを作成することに頭を悩ませたことはありません (方法は知っています)。

これを現実のものにするための例を挙げましょう。次のように使用できる一連のクラスが必要です。

Initialized<T> t;

ここで、T は単純な基本型、PODS、または配列のいずれかです。クラスには独自のコンストラクターが必要であり、生のメモリを上書きすることはひどい考えであるため、クラスにすることはできません。

基本的に初期化する必要があります memset(&t, 0, sizeof(t)); これにより、従来の構造体を扱うときにランタイム コードがデバッグ コードと変わらないことを確認しやすくなります。

Initialized where SDT = simple data type は、基になる SDT をラッパーし、コンパイラ t() を使用してその型のコンパイラ定義のデフォルト コンストラクタを生成する構造体を単純に作成する必要があります (より洗練されているように見えますが、memset にもなる可能性があります)。単純に t() になります。

POD の場合は Initialized<> を、SDT の場合は Initialized<> を使用して、次のように突き刺します。

// zeroed out PODS (not array)
// usage:  Initialized<RECT> r;
template <typename T>
struct Initialized : public T
{
    // ensure that we aren't trying to overwrite a non-trivial class
    BOOST_STATIC_ASSERT((boost::is_POD<T>::value));

    // publish our underlying data type
    typedef T DataType;

    // default (initialized) ctor
    Initialized() { Reset(); }

    // reset
    void Reset() { Zero((T&)(*this)); }

    // auto-conversion ctor
    template <typename OtherType> Initialized(const OtherType & t) : T(t) { }

    // auto-conversion assignment
    template <typename OtherType> Initialized<DataType> & operator = (const OtherType & t) { *this = t; }
};

SDT の場合:

// Initialised for simple data types - results in compiler generated default ctor
template <typename T>
struct Initialised
{
    // default valued construction
    Initialised() : m_value() { }

    // implicit valued construction (auto-conversion)
    template <typename U> Initialised(const U & rhs) : m_value(rhs) { }

    // assignment
    template <typename U> T & operator = (const U & rhs) { if ((void*)&m_value != (void*)&rhs) m_value = rhs; return *this; }

    // implicit conversion to the underlying type
    operator T & () { return m_value; }
    operator const T & () const { return m_value; }

    // the data
    T   m_value;
};

自然なポインターの動作を提供するために、Initialized を T* に特化しました。そして、要素の型と配列サイズの両方をテンプレート引数として受け取る、配列用の InitializedArray<> があります。しかし、繰り返しになりますが、区別するためにテンプレート名を使用する必要があります.1つの名前(理想的にはInitialized<>)からすべてコンパイル時に正しい特殊化をもたらす単一のテンプレートを提供するのに十分なMPLを理解していません.

オーバーロードされた Initialized<typename T, T init_value> も提供できるようになりたいと思っています。これにより、非スカラー値の場合、ユーザーはデフォルトの初期化値 (または memset 値) を定義できます。

回答に少し手間がかかるかもしれない質問をして申し訳ありません。これは、私自身の MPL の読み取りでは克服できなかったハードルのようですが、おそらくあなたの助けがあれば、この機能を突き止めることができるかもしれません!


以下のベンおじさんの回答に基づいて、次のことを試しました。

// containment implementation
template <typename T, bool bIsInheritable = false>
struct InitializedImpl
{
    // publish our underlying data type
    typedef T DataType;

    // auto-zero construction
    InitializedImpl() : m_value() { }

    // auto-conversion constructor
    template <typename U> InitializedImpl(const U & rhs) : m_value(rhs) { }

    // auto-conversion assignment
    template <typename U> T & operator = (const U & rhs) { if ((void*)&m_value != (void*)&rhs) m_value = rhs; return *this; }

    // implicit conversion to the underlying type
    operator T & () { return m_value; }
    operator const T & () const { return m_value; }

    // the data
    T   m_value;
};

// inheritance implementation
template <typename T>
struct InitializedImpl<T,true> : public T
{
    // publish our underlying data type
    typedef T DataType;

    // auto-zero ctor
    InitializedImpl() : T() { }

    // auto-conversion ctor
    template <typename OtherType> InitializedImpl(const OtherType & t) : T(t) { }

    // auto-conversion assignment
    template <typename OtherType> InitializedImpl<DataType> & operator = (const OtherType & t) { *this = t; }
};

// attempt to use type-traits to select the correct implementation for T
template <typename T>
struct Initialized : public InitializedImpl<T, boost::is_class<T>::value>
{
    // publish our underlying data type
    typedef T DataType;
};

そして、いくつかの使用テストを試しました。

int main()
{
    Initialized<int> i;
    ASSERT(i == 0);
    i = 9;  // <- ERROR
}

これにより、エラーが発生します: *binary '=' : no operator found which takes a right-hand operand of type 'InitializedImpl ' (または受け入れ可能な変換がありません)

一方、(派生型ではなく) 正しい基本型を直接インスタンス化する場合:

int main()
{
    InitializedImpl<int,false> i;
    ASSERT(i == 0);
    i = 9;  // <- OK
}

これで、古い int として i を使用できます。これは私が欲しいものです!

構造体に対して同じことをしようとすると、まったく同じ問題が発生します。

int main()
{
    Initialized<RECT> r;
    ASSERT(r.left == 0);  // <- it does let me access r's members correctly! :)

    RECT r1;
    r = r1;  // <- ERROR

    InitializedImpl<RECT,true> r2;
    r2 = r1; // OK
}

ご覧のとおり、コンパイラに Initialized をプロモートして真の T のように動作させるように指示する何らかの方法が必要です。

C++ で基本型から継承できる場合は、継承手法を使用するだけで問題ありません。

または、コンパイラに親から子へのすべてのメソッドを外挿するように指示する方法があれば、親で有効なものはすべて子で有効になるため、問題ありません。

または、必要なものを継承する代わりに、MPL または type-traits を typedef に使用できれば、子クラスはなく、伝播の問題もありません。

アイデア?!...

4

3 に答える 3

2

初期化は基本的にmemset(&t、0、sizeof(t));である必要があります。レガシー構造体を処理するときに、ランタイムコードがデバッグコードと異ならないようにするのが簡単になります。

非PODのデフォルトのコンストラクターを明示的に呼び出すことができるのと同じように、PODをゼロで初期化できるため、memsetは必要ないと思います。(私がひどく間違っていない限り)。

#include <cassert>

struct X {int a, b; };

template <typename T>
struct Initialized
{
    T t;

    // default (initialized) ctor
    Initialized(): t()  { }

};

template <typename T>
struct WithInheritance: public T
{
    // default (initialized) ctor
    WithInheritance(): T()  { }
};

int main()
{
    Initialized<X> a;
    assert(a.t.a == 0 && a.t.b == 0);

    //it would probably be more reasonable not to support arrays,
    //and use boost::array / std::tr1::array instead
    Initialized<int[2]> b;
    assert(b.t[0] == 0 && b.t[1] == 0);

    WithInheritance<X> c;
    assert(c.a == 0 && c.b == 0);
}

タイプのポッド性を判断するために、boost::is_podリファレンスからのこのメモを考慮に入れることもできます。

コンパイラからの(まだ指定されていない)ヘルプがないと、is_podはクラスまたは構造体がPODであることを報告しません。おそらく最適ではない場合でも、これは常に安全です。現在(2005年5月)、MWCW9とVisualC++8のみに必要なコンパイラ組み込み関数があります。

(boost::type_traitsはC++0xの標準ライブラリに組み込まれていると思います。そのような場合、is_pod実際に機能することを期待するのが妥当です。)


ただし、条件に基づいて特殊化する場合は、boolパラメーターを導入できます。たとえば、次のようなものです。

#include <limits>
#include <cstdio>

template <class T, bool b>
struct SignedUnsignedAux
{
    void foo() const { puts("unsigned"); }
};

template <class T>
struct SignedUnsignedAux<T, true>
{
    void foo() const { puts("signed"); }
};

//using a more reliable condition for an example
template <class T>
struct SignedUnsigned: SignedUnsignedAux<T, std::numeric_limits<T>::is_signed > {};

int main()
{
    SignedUnsigned<int> i;
    SignedUnsigned<unsigned char> uc;
    i.foo();
    uc.foo();
}

これもあなたが想像しているように機能するものです(少なくともMinGW4.4とVC++ 2005でコンパイルします-後者は配列がゼロで初期化されるという警告もうまく生成します!:))。

これはデフォルトのブール引数を使用しますが、おそらく自分で指定するべきではありません。

#include <boost/type_traits.hpp>
#include <iostream>

template <class T, bool B = boost::is_scalar<T>::value>
struct Initialized
{
    T value;
    Initialized(const T& value = T()): value(value) {}
    operator T& () { return value; }
    operator const T& () const { return value; }
};

template <class T>
struct Initialized<T, false>: public T
{
    Initialized(const T& value = T()): T(value) {}
};

template <class T, size_t N>
struct Initialized<T[N], false>
{
    T array[N];
    Initialized(): array() {}
    operator T* () { return array; }
    operator const T* () const { return array; }
};

//some code to exercise it

struct X
{
    void foo() const { std::cout << "X::foo()" << '\n'; }
};

void print_array(const int* p, size_t size)
{
    for (size_t i = 0; i != size; ++i) {
        std::cout << p[i] <<  ' ';
    }
    std::cout << '\n';
}

template <class T>
void add_one(T* p, size_t size)
{
    for (size_t i = 0; i != size; ++i) {
        p[i] += T(1);
    }
}

int main()
{
    Initialized<int> a, b = 10;
    a = b + 20;
    std::cout << a << '\n';
    Initialized<X> x;
    x.foo();
    Initialized<int[10]> arr /*= {1, 2, 3, 4, 5}*/; //but array initializer will be unavailable
    arr[6] = 42;
    add_one<int>(arr, 10);  //but template type deduction fails
    print_array(arr, 10);
}

ただし、Initializedはおそらく本物ほど良くはありません。テストコードには1つの欠点が示されています。それは、テンプレートタイプの推測を妨げる可能性があります。また、配列の場合、選択肢があります。コンストラクターを使用してゼロで初期化する場合は、デフォルト以外の配列の初期化を行うことはできません。

初期化されていないすべての変数を追跡し、それらを初期化にラップするという使用法の場合、なぜ自分で初期化しないのかよくわかりません。

また、初期化されていない変数を追跡する場合、コンパイラの警告が大いに役立つ可能性があります。

于 2010-02-10T17:01:14.033 に答える
0

UncleBen の回答を使用して包括的なソリューションを作成できたので (C++ のこの時点で得られると思われる限り)、以下で共有したいと思いました。

自由に使用してください。ただし、使用に値するかどうかについては一切保証しません。大人になって、自分の行動に責任を負ってください。

//////////////////////////////////////////////////////////////
// Raw Memory Initialization Helpers
//
//  Provides:
//      Zero(x) where x is any type, and is completely overwritten by null bytes (0).
//      Initialized<T> x; where T is any legacy type, and it is completely null'd before use.
//
// History:
//
//  User UncleBen of stackoverflow.com and I tried to come up with 
//  an improved, integrated approach to Initialized<>
//  http://stackoverflow.com/questions/2238197/how-do-i-specialize-a-templated-class-for-data-type-classification
//
//  In the end, there are simply some limitations to using this
//  approach, which makes it... limited.
//
//  For the time being, I have integrated them as best I can
//  However, it is best to simply use this feature
//  for legacy structs and not much else.
//
//  So I recommend stacked based usage for legacy structs in particular:
//      Initialized<BITMAP> bm;
//
//  And perhaps some very limited use legacy arrays:
//      Initialized<TCHAR[MAX_PATH]> filename;
//
//  But I would discourage their use for member variables:
//      Initialized<size_t> m_cbLength;
//  ...as this can defeat template type deduction for such types 
//  (its not a size_t, but an Initialized<size_t> - different types!)
//
//////////////////////////////////////////////////////////////

#pragma once

// boost
#include <boost/static_assert.hpp>
#include <boost/type_traits.hpp>

// zero the memory space of a given PODS or native array
template <typename T>
void Zero(T & object, int zero_value = 0)
{
    // ensure that we aren't trying to overwrite a non-trivial class
    BOOST_STATIC_ASSERT((boost::is_POD<T>::value));

    // make zeroing out a raw pointer illegal
    BOOST_STATIC_ASSERT(!(boost::is_pointer<T>::value));

    ::memset(&object, zero_value, sizeof(object));
}

// version for simple arrays
template <typename T, size_t N>
void Zero(T (&object)[N], int zero_value = 0)
{
    // ensure that we aren't trying to overwrite a non-trivial class
    BOOST_STATIC_ASSERT((boost::is_POD<T>::value));

    ::memset(&object, zero_value, sizeof(object));
}

// version for dynamically allocated memory
template <typename T>
void Zero(T * object, size_t size, int zero_value = 0)
{
    // ensure that we aren't trying to overwrite a non-trivial class
    BOOST_STATIC_ASSERT((boost::is_POD<T>::value));

    ::memset(object, zero_value, size);
}

//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////


//////////////////////////////////////////////////////////////////////////
// Initialized for non-inheritable types
// usage: Initialized<int> i;
template <typename T, bool SCALAR = boost::is_scalar<T>::value>
struct Initialized
{
    // ensure that we aren't trying to overwrite a non-trivial class
    BOOST_STATIC_ASSERT((boost::is_scalar<T>::value));

    // the data
    T   m_value;

    // default valued construction
    Initialized() : m_value() { }

    // implicit valued construction (auto-conversion)
    template <typename U> Initialized(const U & rhs) : m_value(rhs) { }

    // assignment
    template <typename U> T & operator = (const U & rhs) { if ((void*)&m_value != (void*)&rhs) m_value = rhs; return *this; }

    // implicit conversion to the underlying type
    operator T & () { return m_value; }
    operator const T & () const { return m_value; }

    // zero method for this type
    void _zero() { m_value = T(); }
};

//////////////////////////////////////////////////////////////////////////
// Initialized for inheritable types (e.g. structs)
// usage:  Initialized<RECT> r;
template <typename T>
struct Initialized<T, false> : public T
{
    // ensure that we aren't trying to overwrite a non-trivial class
    BOOST_STATIC_ASSERT((boost::is_POD<T>::value));

    // default ctor
    Initialized() : T() {  }

    // auto-conversion ctor
    template <typename OtherType> Initialized(const OtherType & value) : T(value) { }

    // auto-conversion assignment
    template <typename OtherType> Initialized & operator = (const OtherType & value) { *this = value; }

    // zero method for this type
    void _zero() { Zero((T&)(*this)); }
};

//////////////////////////////////////////////////////////////////////////
// Initialized arrays of simple types
// usage: Initialized<char, MAXFILENAME> szFilename;
template <typename T, size_t N>
struct Initialized<T[N],false>
{
    // ensure that we aren't trying to overwrite a non-trivial class
    BOOST_STATIC_ASSERT((boost::is_POD<T>::value));

    // internal data
    T m_array[N];

    // default ctor
    //Initialized() : m_array() { } // Generates a warning about new behavior.  Its okay, but might as well not produce a warning.
    Initialized() { Zero(m_array); }

    // array access
    operator T * () { return m_array; }
    operator const T * () const { return m_array; }

    // NOTE: All of the following techniques leads to ambiguity.
    //       Sadly, allowing the type to convert to ArrayType&, which IMO should
    //       make it fully "the same as it was without this wrapper" instead causes
    //       massive confusion for the compiler (it doesn't understand IA + offset, IA[offset], etc.)
    //       So in the end, the only thing that truly gives the most bang for the buck is T * conversion.
    //       This means that we cannot really use this for <char> very well, but that's a fairly small loss
    //       (there are lots of ways of handling character strings already)

    //  // automatic conversions
    //  operator ArrayType& () { return m_array; }
    //  operator const ArrayType& () const { return m_array; }
    // 
    //  T * operator + (long offset) { return m_array + offset; }
    //  const T * operator + (long offset) const { return m_array + offset; }
    // 
    //  T & operator [] (long offset) { return m_array[offset]; }
    //  const T & operator [] (long offset) const { return m_array[offset]; }

    // metadata
    size_t GetCapacity() const { return N; }

    // zero method for this type
    void _zero() { Zero(m_array); }
};

//////////////////////////////////////////////////////////////////////////
// Initialized for pointers to simple types
// usage: Initialized<char*> p;
// Please use a real smart pointer (such as std::auto_ptr or boost::shared_ptr)
//  instead of this template whenever possible.  This is really a stop-gap for legacy
//  code, not a comprehensive solution.
template <typename T>
struct Initialized<T*, true>
{
    // the pointer
    T * m_pointer;

    // default valued construction
    Initialized() : m_pointer(NULL) { }

    // valued construction (auto-conversion)
    template <typename U> Initialized(const U * rhs) : m_pointer(rhs) { }

    // assignment
    template <typename U> T * & operator = (U * rhs) { if (m_pointer != rhs) m_pointer = rhs; return *this; }
    template <typename U> T * & operator = (const U * rhs) { if (m_pointer != rhs) m_pointer = rhs; return *this; }

    // implicit conversion to underlying type
    operator T * & () { return m_pointer; }
    operator const T * & () const { return m_pointer; }

    // pointer semantics
    const T * operator -> () const { return m_pointer; }
    T * operator -> () { return m_pointer; }
    const T & operator * () const { return *m_pointer; }
    T & operator * () { return *m_pointer; }

    // allow null assignment
private:
    class Dummy {};
public:
    // amazingly, this appears to work.  The compiler finds that Initialized<T*> p = NULL to match the following definition
    T * & operator = (Dummy * value) { m_pointer = NULL; ASSERT(value == NULL); return *this; }

    // zero method for this type
    void _zero() { m_pointer = NULL; }
};

//////////////////////////////////////////////////////////////////////////
// Uninitialized<T> requires that you explicitly initialize it when you delcare it (or in the owner object's ctor)
//  it has no default ctor - so you *must* supply an initial value.
template <typename T>
struct Uninitialized
{
    // valued initialization
    Uninitialized(T initial_value) : m_value(initial_value) { }

    // valued initialization from convertible types
    template <typename U> Uninitialized(const U & initial_value) : m_value(initial_value) { }

    // assignment
    template <typename U> T & operator = (const U & rhs) { if (&m_value != &rhs) m_value = rhs; return *this; }

    // implicit conversion to underlying type
    operator T & () { return m_value; }
    operator const T & () const { return m_value; }

    // the data
    T   m_value;
};

//////////////////////////////////////////////////////////////////////////
// Zero() overload for Initialized<>
//////////////////////////////////////////////////////////////////////////

// version for Initialized<T>
template <typename T, bool B>
void Zero(Initialized<T,B> & object)
{
    object._zero();
}
于 2010-02-11T18:05:44.917 に答える
0

私はそれがあなたの質問に答えていないことを知っていますが、とにかくPOD構造は常にゼロで初期化されていると思いました.

于 2010-02-10T16:13:14.427 に答える