Is there a way to make a C++ struct value-initialize all POD member variables?

后端 未结 3 1333
陌清茗
陌清茗 2020-12-01 20:01

Suppose I have a C++ struct that has both POD and non-POD member variables:

struct Struct {
    std::string String;
    int Int;
};

and in

3条回答
  •  心在旅途
    2020-12-01 20:28

    The cleanest way would be to write the auto-initialzed template class initialized:

    EDIT: I realize now it can be made even more flexible by allowing you to declare initialized. This means that you can declare initialization without modifying the original Struct. The default initialization 'T()' was inspired on Prasoons answer.

    template  
    struct initialized 
    { 
    public: 
    
         initialized() 
            { value = T(); }
    
        initialized(T t) 
            { value = t; }
    
        initialized(const initialized& x) 
            { value = x.value; }
    
        T* operator &() { return &value; } 
    
         operator T&() { return value; }     
    
    private: 
         T value; 
    };
    
    
    struct PodStruct 
    {            
        std::string String;      
        int Int; 
    };  
    
    
    struct GlorifiedPodStruct 
    {            
        std::string String;      
        initialized Int; 
    };  
    
    void Test()
    {
        GlorifiedPodStruct s;
        s.Int = 1;
        int b = s.Int;
        int * pointer = &s.Int;
    
        initialized s2;
    }
    

    This compiles, but may need more conversion operators, handling of keywords like volatile, etc. But you get the idea.

提交回复
热议问题