备用模板参数包 [英] Alternating Template Parameters Pack

查看:45
本文介绍了备用模板参数包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得一整套交替的模板参数?

How do I achieve a pack of alternating template parameters?

类似这样的东西:

template< ( unsigned non_type, typename type )... >

必须使用的地方

my_class< 5U, float,
          6U, std::string >

我不想更改订单,也不想在它周围有包装纸使用期间配对。显然,如果在我自己的内部实现中将其分解为一对,就可以了。

I don't want to change the order nor do I want to have a wrapper around it as a pair during usage. Obviously, if it devolves into some sort of a pair in my own internal implementation, that's fine.

推荐答案

要记住的事情模板是不是宏。他们没有在周围复制令牌。它们是真正的C ++结构。每个模板参数必须是特定种类的:类型参数,非类型参数或必须指定其模板参数列表的模板模板参数。模板参数的类型可以使编译器知道在特定位置使用该参数是否有意义。

The thing to remember about templates is that they're not macros. They are not copying tokens around. They're actual C++ constructs. Every template parameter must be of a specific kind: a type parameter, a non-type parameter, or a template-template parameter which must have its template parameter list specified. The kind of a template parameter lets the compiler know whether the use of that parameter in a particular place makes sense.

例如,这可能是有意义的代码:

For example, this is potentially meaningful code:

template<auto value>
auto foo() {return value + 1;}

这显然是胡说: / p>

This is obviously nonsense:

template<typename value>
auto foo() {return value + 1;}

编译器甚至没有必须等待您实例化模板才能关闭它。

The compiler doesn't even have to wait for you to instantiate the template to shut you down.

使用参数包的唯一方法是将其扩展到某个位置。扩展参数包会将使用包的模式应用于包的所有元素。构造一个类型和值都适合该模式的语法的场景非常困难。

The only way to use a parameter pack is to expand it in some location. And expanding a parameter pack applies the pattern which uses the pack to all elements of the pack. It's very difficult to construct a scenario where types and values could both fit into the syntax of the pattern.

当然不是不可能。例如,(pack(something),...)对于类型和非类型模板参数都可能是合法的。但是他们不会做同样的事情。对于值,它将调用该类型上任何可用的 operator();对于类型,它将调用构造函数来创建prvalue。

It isn't impossible to do so, of course. For example, (pack(something), ...) could be legitimate for both type and non-type template parameters. But they won't be doing the same thing. For values, it will be invoking any available operator() on the type; for types, it will be calling a constructor to create a prvalue.

最一般有用的情况是将异构包直接扩展到模板参数列表中。

The most generically useful case would be to expand a heterogeneous pack directly into a template argument list.

但是,所有这些都是诡辩,因为C ++模板不是宏。模板参数必须是定义明确的类型,以便编译器可以知道它们是否被正确使用。这包括参数包。因此,包装中的所有元素都必须是同一类。您想要的将被称为 通用模板参数,但目前仅是一个建议。

However, all of this is sophistry, because C++ templates aren't macros. Template parameters must be of a well-defined kind so that the compiler can know if they are being used properly. And this includes parameter packs. So all elements of a pack must be of the same kind. What you want would be called "universal template parameters", but those are only a proposal at present.

这篇关于备用模板参数包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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