Pippi
Pippi

Reputation: 2571

How can I use a template in C++?

I wish to use a template that has a default parameter l in class A, but the program produces errors:

class B {
 public:
  B(){
  ...
  }
}

template <int l = 1>
class A {
    public: 
  A(const B& b){
  ...
  }
}

int main(){
  B b;

  A(b) a; // error: missing template arguments before '(' token
  A<5>(b) a;    // error: expected ';' before 'a'
} 

How can I fix this?

Upvotes: 0

Views: 104

Answers (5)

David G
David G

Reputation: 96800

A is a template, so you'll have to provide the template brackets irrespective of whether or not it is supplied with a default value.

A<> a(b);

If you don't want to use the template brackets, you can use a typedef declaration to avoid it:

typedef A<> X;

The other errors you are experiencing are due to the fact that you did not end your class definitions with a semicolon.

Here is a working program -- http://ideone.com/occE71#view_edit_box

Upvotes: 0

EHuhtala
EHuhtala

Reputation: 587

you need a semicolon after your class definitions.

Upvotes: 1

Mike Woolf
Mike Woolf

Reputation: 1210

Try A<> a(b); to get the default.

Upvotes: 1

Lu Wang
Lu Wang

Reputation: 356

Try this

A<> a(b);
A<5> a(b);

Upvotes: 3

ecatmur
ecatmur

Reputation: 157334

Just because it's a templated class doesn't change the initialization syntax:

  A<5> a(b);

Using the defaulted parameter:

  A<> a(b);

Upvotes: 1

Related Questions