A
abir
In my program i wan to use a certain type as both type T1 (usually
non-pod)
and also T2 (usually size_t)
so an union like this doesn't work
template<typename T>
union utype{
T v_;
std::size_t sz_;
};
utype* memory_;
where T is
struct nonpod{
int x;
int y;
nonpod(){}
};
I am not familiar to aligned_storage or its usage.
Can i make something like this?
template<typename T,std::size_t N>
struct storage{
typedef std::size_t size_type;
typedef T value_type;
typedef T* pointer;
typedef typename std::tr1::aligned_storage<sizeof(value_type)
,std::tr1::alignment_of<size_type>::value>::type aligned_type;
aligned_type* bos_; ///begin of storage pointer
void init(){
bos_ =
static_cast<aligned_type*>(std::malloc(sizeof(aligned_type)*N));
if(0 == bos_){
throw std::bad_alloc("storage initialization failed");
}
///is it ok? can i treat the memory as sie_type* ?
size_type* p = reinterpret_cast<size_type*>(bos_);
for (size_type i = 0; i != N; ++p){
///is it ok ? ++p goes to next memory location which is
multiple
//of both sizeof(size_type) & sizeof(value_type) ?
*p = ++i;
}
}
};
NOTE: it is ok for me to loose some memory if sizeof(T) <
sizeof(size_type)
or my bookkeeping takes more memory than value_type
Thanks
abir
non-pod)
and also T2 (usually size_t)
so an union like this doesn't work
template<typename T>
union utype{
T v_;
std::size_t sz_;
};
utype* memory_;
where T is
struct nonpod{
int x;
int y;
nonpod(){}
};
I am not familiar to aligned_storage or its usage.
Can i make something like this?
template<typename T,std::size_t N>
struct storage{
typedef std::size_t size_type;
typedef T value_type;
typedef T* pointer;
typedef typename std::tr1::aligned_storage<sizeof(value_type)
,std::tr1::alignment_of<size_type>::value>::type aligned_type;
aligned_type* bos_; ///begin of storage pointer
void init(){
bos_ =
static_cast<aligned_type*>(std::malloc(sizeof(aligned_type)*N));
if(0 == bos_){
throw std::bad_alloc("storage initialization failed");
}
///is it ok? can i treat the memory as sie_type* ?
size_type* p = reinterpret_cast<size_type*>(bos_);
for (size_type i = 0; i != N; ++p){
///is it ok ? ++p goes to next memory location which is
multiple
//of both sizeof(size_type) & sizeof(value_type) ?
*p = ++i;
}
}
};
NOTE: it is ok for me to loose some memory if sizeof(T) <
sizeof(size_type)
or my bookkeeping takes more memory than value_type
Thanks
abir