在对类进行专业化处理时,如何使用不同数量的模板参数? [英] When specializing a class, how can I take a different number of template parameters?

查看:80
本文介绍了在对类进行专业化处理时,如何使用不同数量的模板参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚问了一个问题:我可以获取成员函数模板参数的所属对象吗? Yakk-Adam Nevraumont 的答案中包含以下代码:

I just asked this question: Can I get the Owning Object of a Member Function Template Parameter? and Yakk - Adam Nevraumont's answer had the code:

template<class T>
struct get_memfun_class;

template<class R, class T, class...Args>
struct get_memfun_class<R(T::*)(Args...)> {
    using type=T;
};

这些显然是一个初始声明,然后是struct get_memfun_class的特殊化.但是我发现自己不确定:专业化可以使用不同数量的模板参数吗?

These is clearly an initial declaration and then a specialization of struct get_memfun_class. But I find myself uncertain: Can specializations have a different number of template parameters?

例如,这样合法吗?

template<typename T>
void foo(const T&);

template<typename K, typename V>
void foo<pair<K, V>>(const pair<K, V>&);

是否没有要求专业化必须使用相同数量的参数?

Are there no requirements that specializations must take the same number of parameters?

推荐答案

您似乎混淆了显式专业化的模板参数和用于专业化模板的模板参数.

You seem to confuse the template parameters of the explicit specialization and the template arguments you use to specialize the template.

template<class T> // one argument
struct get_memfun_class; // get_memfun_class takes one template (type) argument

template<class R, class T, class...Args>
struct get_memfun_class<R(T::*)(Args...)> {
//                      ^^^^^^^^^^^^^^^^
//                      one type argument
    using type=T;
}; // explicit specialization takes one template argument

是的,显式专业化具有三个模板参数,但这并不意味着显式专业化具有三个参数.他们在那里被推论.您可以使用多个类型参数来形成单个类型,这就是在那里发生的情况.还请考虑您可以完全专门化模板:

Yes, there are three template parameters for the explicit specialization, but that doesn't mean that the explicit specialization takes three arguments. They are there to be deduced. You can form a single type using multiple type parameters, which is what is happening there. Also consider that you can fully specialize a template:

template <>
struct get_memfun_class<void>;
//                      ^^^^
//                    one type argument

这是同一回事.是的,显式专业化没有参数,但这仅意味着没有要推论的东西,实际上您是在显式地编写模板参数(void),因此专业化的模板参数数量与主模板的模板参数数量匹配

Here it's the same thing. Yes, the explicit specialization takes no parameters, but that just means that there is none to be deduced and indeed you are explicitly writing a template parameter (void) and so the amount of template arguments of the specialization match those of the primary template.

您的示例无效,因为您不能对函数进行部分专业化.

Your example is invalid because you cannot partially specialize functions.

这篇关于在对类进行专业化处理时,如何使用不同数量的模板参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆