One template specialization for multiple classes
You could use std::numeric_limits
to see whether a type is a numeric type (is_specialized
is true for all float and integer fundamental types).
// small utility
template<bool> struct bool2type { };
// numeric
template<typename T>
void fooImpl(T arg, bool2type<true>) {
}
// not numeric
template<typename T>
void fooImpl(T arg, bool2type<false>) {
}
template<class T>
void foo(T arg)
{ fooImpl(arg, bool2type<std::numeric_limits<T>::is_specialized>()); }
With boost:
#include <boost/type_traits/is_scalar.hpp>
#include <iostream>
#include <string>
namespace detail
{
typedef const boost::true_type& true_tag;
typedef const boost::false_type& false_tag;
template <typename T>
void foo(const T& pX, true_tag)
{
std::cout << "special: " << pX << std::endl;
}
template <typename T>
void foo(const T& pX, false_tag)
{
std::cout << "generic: " << pX << std::endl;
}
}
template <typename T>
void foo(const T& pX)
{
detail::foo(pX, boost::is_scalar<T>());
}
int main()
{
std::string s = ":D";
foo(s);
foo(5);
}
You can mostly easily do it without boost:
#include <iostream>
#include <string>
// boolean stuff
template <bool B>
struct bool_type {};
typedef bool_type<true> true_type;
typedef bool_type<false> false_type;
// trait stuff
template <typename T>
struct is_scalar : false_type
{
static const bool value = false;
};
#define IS_SCALAR(x) template <> \
struct is_scalar<x> : true_type \
{ \
static const bool value = true; \
};
IS_SCALAR(int)
IS_SCALAR(unsigned)
IS_SCALAR(float)
IS_SCALAR(double)
// and so on
namespace detail
{
typedef const true_type& true_tag;
typedef const false_type& false_tag;
template <typename T>
void foo(const T& pX, true_tag)
{
std::cout << "special: " << pX << std::endl;
}
template <typename T>
void foo(const T& pX, false_tag)
{
std::cout << "generic: " << pX << std::endl;
}
}
template <typename T>
void foo(const T& pX)
{
detail::foo(pX, is_scalar<T>());
}
int main()
{
std::string s = ":D";
foo(s);
foo(5);
}
You can use an approach with preprocessor.
foo.inc:
template<>
void foo(TYPE arg)
{ /* do something for int, double, etc. */ }
foo.h:
template<class T>
void foo(T arg)
{ /*do something */ }
#define TYPE int
#include "foo.inc"
#undef TYPE
#define TYPE double
#include "foo.inc"
#undef TYPE
etc.