How to explicitly define class with different template arguments?

P

PengYu.UT

Hi,

The following program(doesn't compile) shows that I want to define
class A with different template arguments "int" and "double". Because
class A with int or with double are very different, I have define then
separately.

But it doesn't work. Could you show me the right way?

Best wishes,
Peng

#include <iostream>

template <int>
class A{
public:
A(){ std::cout << "int" << std::endl;}
};

template <double>
class A{
public:
A(){ std::cout << "double" << std::endl;}
};

int main(int argc, char *argv[]) {
A<int> a;
A<double> b;
}
 
R

Rade

But it doesn't work. Could you show me the right way?

You need a template first (at least declared). Then you can specialise it
for int and double. See below.

// First declare the template:
template <typename T> class A;

// You can now specialise it for int...
template <>
class A<int>{ /* ... */ };

// ... and for double...
template <>
class A<double>{ /* .... */ };

Cheers,
Rade
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,294
Messages
2,571,511
Members
48,200
Latest member
SCPKatheri

Latest Threads

Top