Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) TemplateClassExample2

 

STLQt CreatorWindows

 

Template class example 2: class that must be specialized; compile-time polymorphism is a template class example.

 

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: ./CppTemplateClassExample2/CppTemplateClassExample2.pro

 

include(../../ConsoleApplication.pri)
SOURCES += main.cpp

 

 

 

 

 

./CppTemplateClassExample2/main.cpp

 

#include <iostream>

///Template class
template <class T>
struct MyClass
{
  MyClass(const T& x);
};

///Template class specifialized for int, definition in declaration
template <>
struct MyClass<int>
{
  MyClass(const int& x)
  {
    std::cout << "int: " << x << '\n';
  }
};

///Template class specifialized for int, definition seperate after declaration
template <>
struct MyClass<double>
{
  MyClass(const double& x);
};

MyClass<double>::MyClass(const double& x)
{
  std::cout << "double: " << x << '\n';
}

int main()
{
  const MyClass<int> m(123);
  const MyClass<double> n(3.14);

  //Create a MyClass<bool> fails (correctly) with:
  //undefined reference to 'MyClass<bool>::MyClass(bool const&)'
  //const MyClass<bool> q(true);
}

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml