Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) TemplateFunctionExample2

 

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: ./CppTemplateFunctionExample2/CppTemplateFunctionExample2.pro

 

TEMPLATE = app
CONFIG += console
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += main.cpp

CONFIG(release, debug|release) {
  DEFINES += NDEBUG
}

QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Weffc++

unix {
  QMAKE_CXXFLAGS += -Werror
}

win32 {
  INCLUDEPATH += \
    ../../Libraries/boost_1_54_0
}

 

 

 

 

 

./CppTemplateFunctionExample2/main.cpp

 

#include <cassert>
#include <cmath>
#include <string>

struct Data
{
  Data(const int i, const double d, const std::string& s)
    : m_int(i), m_double(d), m_string(s) {}
  int m_int;
  double m_double;
  std::string m_string;
};

template <class T> const T& Get(const Data&);
template <> const int& Get<int>(const Data& d) { return d.m_int; }
template <> const double& Get<double>(const Data& d) { return d.m_double; }
template <> const std::string& Get<std::string>(const Data& d) { return d.m_string; }

int main()
{
  const Data d(42,M_PI,"Hello world");
  assert( Get<int>(d) == 42);
  assert( Get<double>(d) == M_PI);
  assert( Get<std::string>(d) == "Hello world");
}

 

 

 

 

 

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