mardi 4 août 2015

Delegated constructors

I have two questions. Consider this code:

#include <iostream>

struct A {
    A(int n, char c, bool b) 
        /* : some complex initialization list that you don't want to repeat. */
        {initialize();}
    A(int n) : A(n, default_char, default_bool) {}
    A(char c) : A(default_int, c, default_bool) {}  // Do not want initialize() called!
    A(bool b) : A(default_int, default_char, b) {}
    A(int n, char c) : A(n, c, default_bool) {}
    A(int n, bool b) : A(n, default_char, b) {}  // Do not want initialize() called!
    A(char c, bool b) : A(default_int, c, b) {}
private:
    static const int default_int = 3;
    static const char default_char = 't';
    static const bool default_bool = true;
    void initialize() {std::cout << "A ctor.\n";}
};

int main() {
    A a(5,'a',false);
    A b(5);
    A c('a');
    A (5,'a');
    A (5,false);
    A ('a',false);
}

First of all, assuming I want initialize(); to be called for all the constructors of A, is there a way to avoid explicitly repeating the use of default_int, default_char, default_bool, and have them called automatically somehow? Something like

template <typename... Args> A(Args...args) : A(???) {}

Second of all, assume I do NOT want initialize(); to be called for some of the constructors (e.g. stated in the code). How to avoid that without repeating the "complex initialization list" of A(int,char,bool) 's constructor (so as to avoid future maintenance issues)?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire