Pippi
Pippi

Reputation: 2571

How to initiate a class constructor with a class template in C++?

I wish to create an instance of TemplateClassB such that its private tcA is an instance of TemplateClassA with L =1. The program produces an error: no matching function for call to 'TemplateClassA<>::TemplateClassA(TemplateClassA<1>)' : tcA(TemplateClassA<L>(2)){

If I change the TemplateClassB to template <typename E, typename F, int L=5>, then there is no error. Why? How can this be fixed?

template <int L=5>
class TemplateClassA {
public:
  typedef unsigned TypeA;

  TemplateClassA(int i)
    : a(i+L){
  }

  int a;
};

template <typename E, typename F, int L=1>
class TemplateClassB {
public:
  typename TemplateClassA<L>::TypeA var;   

  TemplateClassB()
    : tcA(TemplateClassA<L>(2)){
  }

  TemplateClassA<> tcA;
}; 

int main(){
  TemplateClassA<> A(1);
  TemplateClassB<int, int> B;

}

Upvotes: 2

Views: 89

Answers (3)

billz
billz

Reputation: 45410

tcA is TemplateClassA<5> and you are trying to assignTemplateClassA(2)` to it, they are distinct types.

template <typename E, typename F, int L=1>
class TemplateClassB {
public:
  typename TemplateClassA<L>::TypeA var;   

  TemplateClassB()
    : tcA(TemplateClassA<L>(2)){  // here L is 2
  }

  TemplateClassA<> tcA;  // by default L=5
}; 

you need to write type conversion function or make tcA same type as TemplateClassA<1> which is:

TemplateClassA<L> tcA;  // L is 1 now
//            ^^^

Upvotes: 1

antlersoft
antlersoft

Reputation: 14786

TemplaceClassB::tcA is of type TemplateClassA<5>

With your initial declaration, you are trying to initialize it as if it were TemplateClassA<1>

Upvotes: 1

R Sahu
R Sahu

Reputation: 206567

I think your problem is in the line:

TemplateClassA<> tcA;

Change it to:

TemplateClassA<1> tcA;

Upvotes: 1

Related Questions