Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying template argument

Tags:

c++

templates

How can I specify what is required to be a valid template argument? What I mean is let's for example take something like this:

template<class T>
void f(const T& obj)
{
//do something with obj
} 

but I would like T to be only integer type so I would accept char, int, short unsigned etc but nothing else. Is there (I'm sure there is) a way to detect it what is provided as a template arg?
Thank you.

like image 570
There is nothing we can do Avatar asked May 02 '26 16:05

There is nothing we can do


1 Answers

You can use boost::enable_if and boost::is_integral (also included in the TR1):

#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_integral.hpp>

template <typename T>
typename boost::enable_if<boost::is_integral<T> >::type
f(const T & obj)
{
    ...
}
like image 58
Luc Touraille Avatar answered May 05 '26 06:05

Luc Touraille



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!