Saturday, February 18, 2017

boost enable_if_c example

Consider the following code adapted from Polukhin's book:

#include <iostream>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/type_traits/is_float.hpp>
// Generic implementation
template <class T, class enable = void>
class data_processor {
public:
double process(const T& v1, const T& v2, const T& v3)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
// Integral types optimized version
template <class T>
class data_processor<T, typename boost::enable_if_c<boost::is_integral<T>::value>::type>
{
public:
double process(const T& v1, const T& v2, const T& v3)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
// SSE optimized version for float types
template <class T>
class data_processor<T, typename boost::enable_if_c<boost::is_float<T>::value>::type>
{
public:
double process(const T& v1, const T& v2, const T& v3)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
};
template <class T>
double example_func(T v1, T v2, T v3) {
data_processor<T> proc;
return proc.process(v1, v2, v3);
}
int main () {
// Integral types optimized version will be called
example_func(1, 2, 3);
short s = 0;
example_func(s, s, s);
// Real types version will be called
example_func(1.0, 2.0, 3.0);
example_func(1.0f, 2.0f, 3.0f);
// Generic version will be called
example_func("Hello", "word", "processing");
return 0;
}
view raw c.cpp hosted with ❤ by GitHub

When run:

kuyu@ub16:~/dkuyu/Dropbox/practice/cpp/boost/polukhin/ch04/enable_if_c$ g++ -I~/dkuyu/bin/boost_1_60_0 c.cpp && ./a.out
double data_processor<T, typename boost::enable_if_c<boost::is_integral<T>::value>::type>::process(const T&, const T&, const T&) [with T = int; typename boost::enable_if_c<boost::is_integral<T>::value>::type = void]
double data_processor<T, typename boost::enable_if_c<boost::is_integral<T>::value>::type>::process(const T&, const T&, const T&) [with T = short int; typename boost::enable_if_c<boost::is_integral<T>::value>::type = void]
double data_processor<T, typename boost::enable_if_c<boost::is_float<T>::value>::type>::process(const T&, const T&, const T&) [with T = double; typename boost::enable_if_c<boost::is_float<T>::value>::type = void]
double data_processor<T, typename boost::enable_if_c<boost::is_float<T>::value>::type>::process(const T&, const T&, const T&) [with T = float; typename boost::enable_if_c<boost::is_float<T>::value>::type = void]
double data_processor<T, enable>::process(const T&, const T&, const T&) [with T = const char*; enable = void]

No comments:

Post a Comment