Constructors, templates and non-type parameters

前端 未结 3 1372
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 16:47

I\'ve a class that must depend for some reasons from an int template parameter.
For the same reasons, that parameter cannot be part of the parameter list fo

3条回答
  •  渐次进展
    2021-01-01 17:10

    I think that solution with "traits" is the best for most cases.

    Only to make a little more "mess" in this issue I will provide two more alternatives. Maybe in some very specific cases - they can be in some way better.


    1. Template global variable - you can name it a prototype solution:

    class C only differs in its constructor from your original code:

    class C final {
        // All B and D defined as in OP code
     public:
        // Here the change - c-tor just accepts D 
        template 
        explicit C(D* b) : b(b) {}
    
        // all the rest as in OP code
    };
    

    The prototype - template global variable:

    template 
    C c{new C::D()}; 
    // this variable should be rather const - but foo() is not const 
    // and copy semantic is not implemented...
    

    And usage:

    int main() {
        // you did not implement copy semantic properly - so just reference taken
        C& c = ::c<3>; 
        c.foo();
    }
    

    1. Solution with Base class - and derive class depending on int

    This solution, although looks pretty promising I would personally avoid - that only complicates design - and some possibility of object slicing is here present too.

    class CBase {
        // all here as in OP code for C class
    public:
        // only difference is this constructor:
        template
        explicit CBase(D* b) : b(b) {}
    };
    

    Then - the final class:

    template 
    class C final : private CBase {
    public:
        C() : CBase(new CBase::D()) {}
        using CBase::foo;
    };
    

    The usage:

    int main() {
        C<3> c;
        c.foo();
    }
    

    Q: One can ask in which way solution with Base class is better than just adding int as another parameter.
    A: by base implementation class you do not need to have many "copies" of the same code - you avoid template code bloat...

提交回复
热议问题