我们使用boost - 所以使用该库应该没问题。
但是我从来没有设法围绕创建一组模板,这些模板为整个类数据类型提供了正确的专业化,而不是专门针对单一数据类型(我知道如何做)
让我举一个例子来试图把它带到地上。我想有一组可以用作的类:
Initialized<T> t;
其中T是简单的基本类型,PODS或数组。它不能是一个类,因为一个类应该有自己的构造函数,并且覆盖它的原始内存是一个糟糕的主意。
初始化应该基本上是memset(&amp; t,0,sizeof(t));在处理遗留结构时,它可以更容易确保运行时代码与调试代码没有区别。
初始化SDT =简单数据类型的地方,应该简单地创建一个包装底层SDT的结构,并使用编译器t()生成该类型的编译器定义的默认构造函数(它也可以构成一个memset,尽管它简单地导致t()似乎更优雅。
使用Initialized&lt;&gt;进行攻击。对于POD,并且已初始化&lt;&gt;对于SDT:
// 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;
};
我专门为T *初始化,以提供自然的指针行为。我有一个InitializedArray&lt;&gt;对于数组,它将元素类型和数组大小都作为模板参数。但同样,我必须使用模板名称来区分 - 我不能很好地理解MPL以提供单个模板,从而在编译时从单个名称(Initialized&lt;&gt;,理想情况下)生成正确的特化。
我也希望能够提供重载的Initialized&lt; typename T,T init_value&gt;同样,对于非标量值,用户可以定义默认初始化值(或memset值)
我为要求可能需要付出一些努力的东西而道歉。这似乎是我自己在自己的MPL阅读中无法克服的障碍,但也许在你的一些帮助下我可以将这个功能放下来!
根据Ben叔叔的回答,我尝试了以下内容:
// 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'=':找不到带有'InitializedImpl '类型的右手操作数的操作符(或者没有可接受的转换)
然而,如果我直接实例化正确的基类型(而不是派生类型):
int main()
{
InitializedImpl<int,false> i;
ASSERT(i == 0);
i = 9; // <- OK
}
现在我可以使用i作为任何旧的int。这就是我想要的!
如果我尝试对结构进行相同的操作,则会出现完全相同的问题:
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来输入type而不是继承我需要的东西,那么就没有子类,也没有传播问题。
想法?!...
答案 0 :(得分:2)
基本上应该初始化 memset(&amp; t,0,sizeof(t));它成功了 更容易确保运行时代码 与调试代码没有什么不同 处理遗留结构。
我认为您不应该需要memset,因为您可以对POD进行零初始化,就像您可以显式调用非POD的默认构造函数一样。 (除非我非常错误)。
#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);
}
在你确定类型的pod-ness的过程中,你也可以考虑来自boost :: is_pod引用的这个注释:
没有一些(尚未指明)的帮助 从编译器来看,is_pod永远不会 报告一个类或结构是一个 荚;如果可能的话,这总是安全的 次优的。目前(仅限2005年5月) MWCW 9和Visual C ++ 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();
}
这也有点像你想象的那样(至少用MinGW 4.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可能永远不会像真实的那样好。测试代码中显示了一个短缺:它可能会干扰模板类型扣除。此外,对于数组,您可以选择:如果您想使用构造函数对其进行零初始化,则不能进行非默认数组初始化。
如果用法是你要追踪所有未初始化的变量并将它们包装成Initialized,我不太清楚为什么你不会自己初始化它们。
此外,为了追踪未初始化的变量,编译器警告可能会有很大帮助。
答案 1 :(得分:0)
我知道它没有回答你的问题,但我认为POD结构总是零初始化。
答案 2 :(得分: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();
}