C++ template specialization of constructor

后端 未结 7 905
醉话见心
醉话见心 2021-02-05 17:15

I have a templated class A and two typedefs A and A. How do I override the constructor for A ? The following does not wor

相关标签:
7条回答
  • 2021-02-05 17:53

    Assuming your really meant for A::test to be publicly accessible, you could do something like this:

    #include <iostream>
    
    
    template <int M>
    struct ABase
    {
      ABase(int n) : test_( n > M )
      {}
    
      bool const test_;
    };
    
    
    template <typename T, int M>
    struct A : ABase<M>
    {
      A(int n) : ABase<M>(n)
      {}
    };
    
    
    template <typename T>
    A<T, 20>::A(int n)
      : ABase<20>(n)
      { std::cerr << "One type" << std::endl; }
    

    Kick the tires:

    int main(int argc, char* argv[])
    {
      A<int, 20> a(19);
      std::cout << "a:" << a.test_ << std::endl;
      A<int, 30> b(31);
      std::cout << "b:" << b.test_ << std::endl;
      return 0;
    }
    
    0 讨论(0)
提交回复
热议问题