Reputation: 6255
I have designed my own implementation of std::vector which I call il::vector. I would like either to:
memcpy
(int
, double
, std::array<double, n>
, etc..).memcpy
such as std::vector
. In the latter case, I want to have a compile-time error if I want to instantiate with something that can't be copied with memcpy
, such as il::vector<std::vector<double>>
.Is there a way to do that ?
PS: I always get answer such as: you should use std::vector instead. The main reasons I use my own library are:
Sorry to be a little bit rude, but I am sick of: STL is god, don't even say that it does not fit your needs.
Upvotes: 0
Views: 272
Reputation: 218288
Since C++11, you may use traits std::is_trivially_copyable
.
For an error case, may do something like:
namespace il
{
template <typename T /*, typename Allocator*/>
class vector
{
static_assert(std::is_trivially_copyable<T>::value, "type should be trivially copyable");
/* Your implementation */
};
}
To select different implementations you may use std::conditional
template <typename T /*, typename A*/>
using myvector = typename std::conditional<std::is_trivially_copyable<T>::value,
il::vector<T>,
std::vector<T>
>::type
Upvotes: 3
Reputation: 1759
You can use the type trait is_trivially_copyable in conjunction with static assert.
template<typename T>
class IlVector {
static_assert(is_trivially_copyable<T>::value,
"Vector requires memcpy able type");
// ...
};
int main() {
IlVector<int> a;
IlVector<double> b;
IlVector<std::array<int,3> > c;
IlVector<std::string> d;
// your code goes here
return 0;
}
This will give you an compile time error if your type cannot be copied by memcpy.
Upvotes: 2