[英]template method specialization inside template class
I need (want) to specialize a method inside a template class, to allow only certain primitive types. 我需要(想要)专门化模板类中的方法,只允许某些基本类型。 (This is not a duplicate question of this )
(这不是一个重复的问题, 这个 )
Well i've got 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 allow only unsigned integers, something like this : 我想专门化arg_type只允许无符号整数,如下所示:
template<typename TYPE, size_t NB> template<unsigned long> X& X::get(const unsigned long val);
But sure, the above doesn't work, neither on msvc2011 nor on gcc 但可以肯定的是,上述内容在msvc2011和gcc上都不起作用
To be more specific, what i try to do is to write a code based on the templated type above, and write the specialization so that anyone using this class X cannot use this method with something else than what i specialized. 更具体地说,我尝试做的是基于上面的模板化类型编写代码,并编写专门化,以便使用此类X的任何人都不能使用此方法而不是我专门的方法。
Is that even possible ? 这甚至可能吗? and if it is, is it bad to do it so ?
如果是的话,这样做是不是很糟糕?
Thanks in advance, jav974 在此先感谢,jav974
A specialization is not what you want. 专业化不是你想要的。 Using a specialization you can provide a special way to treat the instantiation of your template method using an unsigned integral type, but nothing prevents the user from instantiating it with another type.
使用专门化,您可以使用无符号整数类型提供一种特殊的方法来处理模板方法的实例化,但没有什么可以阻止用户使用其他类型实例化它。
You can achieve this using some SFINAE : 您可以使用一些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)
{
}
};
You could also use static_assert
, so that users get a more friendly error message: 您还可以使用
static_assert
,以便用户获得更友好的错误消息:
template<typename arg_type>
X& get(arg_type val)
{
static_assert(std::is_unsigned<arg_type>::value, "The argument should be unsigned!");
}
If you want the TYPE
template parameter to follow the same rules, you could also use static_assert
: 如果您希望
TYPE
模板参数遵循相同的规则,您还可以使用static_assert
:
template<typename TYPE, size_t NB>
class X
{
public:
static_assert(std::is_unsigned<TYPE>::value, "TYPE should be unsigned!");
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.