Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 606447
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T17:15:19+00:00 2026-05-13T17:15:19+00:00

We use boost – so using that library should be fine. But I’ve never

  • 0

We use boost – so using that library should be fine.

But I’ve never managed to wrap my head around creating a set of templates which give you the right specialization for a whole class of data types, as opposed to specializing for a single data type (which I know how to do).

Let me go for an example to try to bring this down to earth. I want to have a set of classes which can be used as:

Initialized<T> t;

Where T is either a simple basic type, a PODS, or an array. It cannot be a class, for a class is expected to have its own constructor, and overwriting its raw memory is a terrible idea.

Initialized should basically memset(&t, 0, sizeof(t)); It makes it easier to ensure that runtime code is not different from debug code when dealing with legacy structs.

Initialized where SDT = simple data type, should simply create a struct which wrappers the underlying SDT and uses the compilers t() to generate the compiler defined default constructor for that type (it could amount to a memset as well, though it seems more elegant to simply result in t().

Here’s a stab at it, using Initialized<> for PODs, and Initialised<> for SDTs:

// 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; }
};

And for SDTs:

// 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;
};

I have specialized Initialised for T*, to provide natural pointer behaviors. And I have an InitializedArray<> for arrays, which takes both the element type and array-size as template arguments. But again, I have to use template name to distinguish – I don’t grok MPL well enough to provide a single template that results in the correct specialization at compile time all from a single name (Initialized<>, ideally).

I would love also to be able to provide an overloaded Initialized<typename T, T init_value> as well, so that for non-scalar values the user could define the default initialization value (or memset value)

I apologize for asking something that may take a bit of effort to answer. This seems to be a hurdle that I haven’t been able to overcome in my own MPL reading on my own, but perhaps with some of your help I may be able to nail this functionality down!


Based on Uncle Ben’s answer(s) below, I tried the following:

// 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;
};

And then tried a couple of usage tests.

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

This results in an error: *binary ‘=’ : no operator found which takes a right-hand operand of type ‘InitializedImpl ‘ (or there is no acceptable conversion)

Whereas if I directly instantiate the correct base type (instead of a derived type):

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

Now I can use i as any old int. Which is what I want!

The exact same problems arise if I try to do the same for structs:

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
}

So, as you can see, I need some way to tell the compiler to promote an Initialized to act like a true T.

If C++ let me inherit from basic types, I could just use the inheritance technique and all would be well.

Or if I had some way to tell the compiler to extrapolate all methods in parent to child, so that anything valid on parent was valid on child, I’d be okay.

Or if I could use MPL or type-traits to typedef instead of inherit what I need, then there would be no child class, and no propagation issue.

Ideas?!…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T17:15:19+00:00Added an answer on May 13, 2026 at 5:15 pm

    Initialized should basically
    memset(&t, 0, sizeof(t)); It makes it
    easier to ensure that runtime code is
    not different from debug code when
    dealing with legacy structs.

    I don’t think you should need memset, because you can zero-initialize PODs just as you can explicitly invoke the default constructor of non-PODs. (unless I’m terribly mistaken).

    #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);
    }
    

    In your quest to determine the pod-ness of a type, you might also take into account this note from boost::is_pod reference:

    Without some (as yet unspecified) help
    from the compiler, is_pod will never
    report that a class or struct is a
    POD; this is always safe, if possibly
    sub-optimal. Currently (May 2005) only
    MWCW 9 and Visual C++ 8 have the
    necessary compiler intrinsics.

    (I think boost::type_traits are making it into the standard library in C++0x, and in such a case it would be reasonable to expect an is_pod that actually works.)


    But if you want to specialize based on a condition, you can introduce a bool parameter. E.g something like this:

    #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();
    }
    

    Here’s also something that works sort of like you might be imagining (compiles at least with MinGW 4.4 and VC++ 2005 – the latter also nicely produces a warning that the array will be zero-initialized! :)).

    This uses a default boolean argument which you probably shouldn’t ever specify yourself.

    #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);
    }
    

    However, Initialized will probably never be as good as the real thing. One short-coming is shown in the test code: it can interfere with template type deduction. Also, for arrays you’ll have a choice: if you want to zero-initialize it with the constructor, then you can’t have non-default array initialization.

    If the usage is that you are going to track down all uninitialized variables and wrap them into Initialized, I’m not quite sure why you won’t just initialized them yourself.

    Also, for tracking down uninitialized variables, perhaps compiler warnings can help a lot.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 357k
  • Answers 357k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You probably want to call setlocale() first, "LC_ALL" should do… May 14, 2026 at 9:06 am
  • Editorial Team
    Editorial Team added an answer Linux Ubuntu Desktop Jaunty Firebug FireCookie Pixel Perfect Web developer… May 14, 2026 at 9:06 am
  • Editorial Team
    Editorial Team added an answer Your code should look like this: var par = [];… May 14, 2026 at 9:06 am

Related Questions

std::auto_ptr is broken in VC++ 8 (which is what we use at work). My
The thing that really turns me off about Boost is their documentation. What I
I was asking my team to port our vc6 application to vc2005, they are
We have a large Visual Studio 2005 C++/Mfc solution, 1 project with around 1300
Let's say I have 3 classes. I expect sizeof() each class to be exactly

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.