Specifying a Template Argument

How can I indicate what is required for a valid template argument? I mean, for example, let's say something like this:

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

but I would like T to be only an 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, which is provided as an arg pattern?
Thank.

+3
source share
3 answers

boost:: enable_if boost:: is_integral ( 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)
{
    ...
}
+5

, , ( ).

++ 0x:

#include <utility>

template <class T>
void foo(T )
{
    static_assert(std::is_integral<T>::value, "Only integral types allowed");
}

int main()
{
    foo(3);    //OK
    foo(3.14); //makes assertion fail
}

++ 03, boost :

#include <boost/type_traits.hpp>
#include <boost/static_assert.hpp>

template <class T>
void foo(T )
{
    BOOST_STATIC_ASSERT(boost::is_integral<T>::value);
}

int main()
{
    foo(3);
    foo(3.14);
}

(IMO, enable_if , - . , , : " ", , .)

+2

Source: https://habr.com/ru/post/1756705/


All Articles