如何在之前声明的另一个模板参数中使用模板参数 [英] How to use a template parameter in another template parameter declared before

查看:105
本文介绍了如何在之前声明的另一个模板参数中使用模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个模板参数可以用在它后面的另一个模板参数中:

a template parameter can be used in another template parameter that follows it this way :

template<typename T, T N>
struct s
{
};

但是如果在"N"之后声明它,是否可以引用"T"?

But is it possible to reference "T" if it is declared after "N" ?

这不起作用:

template<T N, typename T>
struct s
{
};

我们可以通过预先声明"T"或执行其他任何操作来帮助编译器吗?

Can we help the compiler by pre-declaring "T" or doing anything else ?

多谢.

由于前两个答复都在问您为什么愿意这样做?"我将解释目标:

EDIT : as the first two replies were asking "why are you willing to do that ?" I'll explain the goal :

我想让编译器推断类型"T",以便更轻松地使用模板化类.

I would like to make the compiler infer the type "T" in order to make the use of templated classes easier.

例如:

template<typename T, T A, T B>
struct sum
{
    static T const value = A + B;
};

可以以这种方式使用此模板:

This template can be used this way :

sum<int, 1, 2>::value

但是如果可以这样使用它会更好:

But it would be better if it could be used this way :

sum<1, 2>::value

从技术上讲,这是有可能的,因为编译器知道"1"和"2":"int"的类型,实际上,它使用这些信息来查找函数的最佳重载. 因此,通过这种方式声明模板:

Technically it's should be possible because the compiler knows the types of "1" and "2" : "int", and in fact it uses these informations to find the best overload for a function. So by declaring the template this way :

template<T A, T B, typename T>
struct sum
{
    static T const value = A + B;
};

编译器可以使用其功能从第一个和第二个提供的信息中推断出最后一个参数,然后找到最佳实例化模板.

the compiler could use its capability to infer the last parameter from the informations provided by the first and the second one, and then find the best template to instantiate.

推荐答案

就像其他人说的那样-不行,这是不可能的,编译器无法从非类型 template <推断T的类型参数(对于函数,它从 function 参数推断类型):

Like others say - No this isn't possible, the compiler can't infer the type of T from the non-type template arguments (in the case of functions, it infers types from the function arguments):

14.8.2.4/12:

不能从非类型模板参数的类型推导出模板类型参数.

A template type argument cannot be deduced from the type of a non-type template-argument.

在任何情况下,无论如何都不会对类模板的参数进行推论.功能模板的示例可能是

In any case, no deduction will be made for the arguments of a class template anyway. An example for a function template might be

template<int> struct having_int { };
template<typename T, T i> void f(having_int<i>);
int main() { having_int<0> h; f(h); }

在这种情况下,不会将T推导出为int-您必须明确指定它.

In this case, T won't be deduced as int - you have to explicitly specify it.

这篇关于如何在之前声明的另一个模板参数中使用模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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