Method template specialization within the template class

I need to (want to) specialize the method inside the template class to allow only certain primitive types. (This is not a duplicate question this )

Well, I have this class:

template<typename TYPE, size_t NB>
class X
{
public:
   template<typename arg_type>
   X& get(const arg_type var);
}

I would like to specialize arg_type to only allow unsigned integers, something like this:

template<typename TYPE, size_t NB> template<unsigned long> X& X::get(const unsigned long val);

But, of course, the above does not work, neither on msvc2011, nor on gcc

To be more specific, I am trying to write code based on the template type above and write a specialization so that someone using this X class cannot use this method with anything other than what I specialized.

Is it possible? and if so, is it bad to do this?

Thanks in advance, jav974

+5
source share
1

- , . , , .

, SFINAE:

#include <type_traits>    

template<typename TYPE, size_t NB> 
class X
{
public:
    template<typename arg_type> 
    typename std::enable_if<std::is_unsigned<arg_type>::value, X&>::type  // arg_type is unsigned
    get(arg_type val) 
    {

    }
};

static_assert, :

template<typename arg_type> 
X& get(arg_type val) 
{
    static_assert(std::is_unsigned<arg_type>::value, "The argument should be unsigned!");
}

, TYPE , static_assert:

template<typename TYPE, size_t NB> 
class X
{
public:
    static_assert(std::is_unsigned<TYPE>::value, "TYPE should be unsigned!");
};
+4

All Articles