Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

How to pass template of Anythings as template parameter in C++?

To have any types in template one may just write template <typename ...> struct S {};.

To have any values (e.g. int values) in template one may write template <auto ...> struct S {};.

To have template of any types in template one writes template <template <typename ...> class Tmpl> struct S {};.

But how to have template of Anythings in template? Anythings meaning 1) types or 2) values or 3) other templates of Anythings? I.e. mix everything what is possible inside template.

I.e. how to write template <template <Anything ...> class Tmpl> struct S {};

types/values/templates can be mixed in any order inside Tmpl parameters list.

One use case for having such structure S that accepts any kind of template is to implement template traits, i.e. so that S can tell somehow 1) how many parameters Tmpl has. 2) for each of parameter (by index) it can tell if it is type or value or another template.

Another use case for S is that it is needed to implement rich compile time information. I.e. if I can tell all the information about passed-in template, how many and what params it has, then I can compose composite Type Id or Type Name recursively and thus have compile time type reflection.

Also I'm interested in knowing how to intermix at least types and values inside one template in arbitrary order? I.e. how to have template <TypeOrValue ... Args> struct S {};? Here TypeOrValue signifies either typename or auto in any order or count.

question from:https://stackoverflow.com/questions/65895495/how-to-pass-template-of-anythings-as-template-parameter-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Strictly speaking, you cannot do what you're asking for. But what you can do is represent values as a special type, and then intermix that special type with other "normal" types. E.g., a helper could look something like this (untested code):

template<auto v>
struct value {};

Then any occurrence of value<...> would indicate that a value was meant, not a type. Doing anything useful with this can be finicky as you would have to handle value<...> specially, but it can work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...