Go back to Richel Bilderbeek's homepage.

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

 

 

 

 

 

(C++) StdEnable_ifExample1

 

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: ./CppStdEnable_ifExample1/CppStdEnable_ifExample1.pro

 

include(../../ConsoleApplication.pri) #Or use the code below
# QT += core
# QT += gui
# greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
# CONFIG   += console
# CONFIG   -= app_bundle
# TEMPLATE = app
# CONFIG(release, debug|release) {
#   DEFINES += NDEBUG NTRACE_BILDERBIKKEL
# }
# QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Weffc++
# unix {
#   QMAKE_CXXFLAGS += -Werror
# }

include(../../Libraries/Boost.pri) #Or use the code below
# win32 {
#   INCLUDEPATH += \
#     ../../Libraries/boost_1_54_0
# }

SOURCES += main.cpp

 

 

 

 

 

./CppStdEnable_ifExample1/main.cpp

 

//Adapted from http://www.cplusplus.com/reference/type_traits/enable_if

// enable_if example: two ways of using enable_if
#include <iostream>
#include <type_traits>

// 1. the return type (bool) is only valid if T is an integral type:
template <class T>
typename std::enable_if<
  std::is_integral<T>::value,bool>::type
  is_odd(const T i)
{
  return static_cast<bool>(i%2);
}

// 2. the second template argument is only valid if T is an integral type:
template <class T,
  class = typename std::enable_if<std::is_integral<T>::value>::type>
bool is_even (T i)
{
  return !static_cast<bool>(i%2);
}

int main()
{
  const int i = 1; //code does not compile if type of i is not integral
  std::cout
    << "i is odd : " << is_odd(i) << '\n'
    << "i is even: " << is_even(i) << '\n';
}

 

 

 

 

 

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