How to forward overloaded constructor call to another constructor in C++/CLI

前端 未结 4 815
醉酒成梦
醉酒成梦 2020-12-20 17:50

I know that there is no way to do this in pure C++, but I was wondering if it is possible to call a constructor from another constructor\'s initialization list in C++/CLI, s

4条回答
  •  悲&欢浪女
    2020-12-20 18:28

    Just stumbled by, for the same question. In my case I'm using VS2010.

    It is clear that VS2010 will never get updated to fully implement C++11, use VS2015 if you need better compliance with the standard (which I do when I can). But for some (legacy) projects I still have to use VS2010.

    An approach that works in many cases (for me) is the use of a private function with all shared initialisation code in it. Example:

    class A
    {
    private:
        void Inidialise() { /* common initialisation here */ }
    
    public:
        A()       { Initialise(); /* specific initialisation for A() here */ }
        A(bool a) { Initialise(); /* specific initialisation for A(bool) here */ }
        A(int b)  { Initialise(); /* specific initialisation for A(int) here */ }
    
        /* etcetera */
    
    }
    

    It does not solve all 'problems' and it does not prevent all cases of duplicate code but it goes a long way.

提交回复
热议问题