非类型模板参数的使用情况,不是积分/枚举类型? [英] Use case for non-type template parameter that's not of integral/enumeration type?

查看:314
本文介绍了非类型模板参数的使用情况,不是积分/枚举类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++允许非类型模板参数是整数或枚举类型(整数包括布尔值和字符),以及指针和任意类型的引用。



我已经看到整数,布尔和枚举参数广泛使用,我欣赏他们的实用程序。我甚至看到了对字符参数的巧妙使用,用于字符串的编译时解析。 / p>

但我想知道非类型模板参数的一些用例是指针或任意类型的引用?

解决方案

使用指针到成员函数作为模板参数,使编译器可以内联对该函数的调用。这个用法的一个例子可以在我的回答这个问题看到:如何允许模板函子在成员函数和非成员函数上工作



在此示例中,模板参数中的指针到成员函数使得能够生成包含对指针到成员函数的调用(内联)的thunk函数。指向thunk函数的指针有一个通用的签名(和固定大小),它能够以最小的运行时间成本进行存储和复制,而不像指针成员函数。


C++ allows non-type template parameters to be of integral or enumeration type (with integral including boolean and character), as well as pointers and references to arbitrary types.

I have seen integer, boolean, and enumeration parameters used widely and I appreciate their utility. I've even seen a clever use of character parameters for compile-time parsing of strings.

But I'm wondering what are some use cases for non-type template parameters that are pointers or references to arbitrary types?

解决方案

Using a pointer-to-member-function as a template parameter makes it possible for the compiler to inline a call to that function. An example of this usage can be seen in my answer to this question: How to allow templated functor work on both member and non-member functions

In this example, the pointer-to-member-function in the template parameter enables the generation of a 'thunk' function that contains a call (inlined) to the pointer-to-member-function. A pointer to the thunk function has a generic signature (and fixed size) which enables it to be stored and copied with minimal runtime cost, unlike a pointer-to-member-function.

这篇关于非类型模板参数的使用情况,不是积分/枚举类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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