wyn...@gmail.com writes:
> How should the idea be implemented to instantiate different definition
> of ctors from the template parameter Memcpy_able?
>
> //----- file t1.cpp -----
>
> #include <iostream>
> #include <string.h> // for memcpy
>
> template<typename T, bool Memcpy_able>
> class Vect {
> T m_0, m_1, m_2;
>
> public:
>
> // Memcpy_able is false (how to enable this definition and the next one
> // for different value of Memcpy_able?)
> //
> // Vect(const T(&arr)[3])
> // : m_0(arr[0]), m_1(arr[1]), m_2(arr[2]) {};
>
> // Memcpy_able is true
> // (Let's assume memcpy can work correctly for the moment)
>
> Vect(const T(&arr)[3]) {
> ::memcpy(&m_0,arr,sizeof(this));
> };
> };
What I would do is pull out these class members into a different template,
and simply specialize it, then have this `Vect` inherit from it, something
like:
template<typename T, bool Memcpy_able> class Vect_base;
template<typename T>
class Vect_base<T, false> {
protected:
T m_0, m_1, m_2;
// First constructor
};
template<typename T>
class Vect_base<T, true> {
protected:
T m_0, m_1, m_2;
// First constructor
};
// If the constructor doesn't need anything else to do, simply inherit it:
template<typename T, bool Memcpy_able>
class Vect : Vect_base<T, Memcpy_able> {
public:
using Vect_base::Vect_base;
It's possible that Vect's 2nd template parameter won't be needed at all, and
it can figure out what it must be, for the inherited superclass.
> Another question is, while trying out the solution, I guessed some rule
> of c++ (or g++) might have changed because the value sizeof(Vect<char,true>)
> was used to 3*4=12, not 3. Can someone explain this?
>
> [me@localhost]$ g++ t1.cpp
> [me@localhost]$ ./a.out
> 3
No rule of C++ has changed. Padding required by classes or class members is
always implementation defined, and can change from compiler to compiler, or
compiler version.
You cannot assume that there is, or isn't, padding between class members.