Constructors, templates and non-type parameters

前端 未结 3 1382
没有蜡笔的小新
没有蜡笔的小新 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:30

    use template specialization and inheritance:

    #include 
    using namespace std;
    
    template  struct A {
        A() { cout << "generic" << endl; }
    };
    
    template <> struct A<1> {
        A() { cout << "implementation of 1" << endl; }
    };
    
    template 
    struct B : public A {
        B() : A() {}
    };
    
    int main(int argc, char *argv[])
    {
        B<1> b;
        B<3> b1;
        B<4> b2;
    }
    

    edit: or you can do it even easier:

    template 
    struct A {
        A();
    };
    
    template 
    A::A() { cout << "general " << num << endl; }
    
    template <>
    A<1>::A() { cout << "specialization for 1" << endl; }
    

提交回复
热议问题