C模板参数推断

前端之家收集整理的这篇文章主要介绍了C模板参数推断前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
作为练习我试图使用模板编写数组实现,但使用函数指针作为模板参数.每次对数组进行索引时都会调用函数.
  1. template<typename T,int size>
  2. using Array_fnIndex = void (*)(int index);
  3.  
  4. template<typename T,int size,typename Array_fnIndex<T,size> fnIndex>
  5. struct Array {
  6. T data[size];
  7. T& operator[](int index) {
  8. fnIndex(index);
  9. return data[index];
  10. }
  11. };
  12.  
  13. // example index function
  14. template<typename T,int size>
  15. void checkIndex(int index) {
  16. assert(index < size);
  17. }
  18.  
  19. int main() {
  20. Array<int,10,checkIndex<int,10>> a; // this works
  21. Array<int,11>> b; // this also works,not what I want
  22. Array<int,checkIndex> c; // this doesn't work,but what I want
  23. return 0;
  24. }

main函数中的最后一个Array声明是我想要的,其中checkIndex的模板参数与Array中的先前模板参数匹配.但是这不能编译(使用Microsoft编译器).我收到以下错误

  1. error C2440: 'specialization': cannot convert from 'void (__cdecl *)(uint)' to 'void (__cdecl *)(uint)'
  2. note: None of the functions with this name in scope match the target type

有没有办法获得所需的结果,其中提供的函数的模板参数从其他参数推断?

解决方法

可能不适用于您的实际用例,但我建议一个包含执行检查的函数的可调用对象:
  1. template<typename T,typename fnIndex>
  2. struct Array {
  3. T data[size];
  4. T& operator[](int index) {
  5. fnIndex{}.template check<size>(index);
  6. return data[index];
  7. }
  8. };
  9.  
  10. struct checkIndex {
  11. template<int size>
  12. void check(int index) {
  13. assert(index < size);
  14. }
  15. };
  16.  
  17. int main() {
  18. Array<int,checkIndex> c;
  19. return 0;
  20. }

wandbox example

让我们分析fnIndex {}.模板检查< size>(索引):

  1. fnIndex{} // make a temporary object of type `fnIndex`
  2. .template check<size>(index) // call its `check` method using `size`
  3. // as a template argument and `index` as
  4. // as a function argument

.template消歧语法是必需的,因为编译器不知道检查的含义 – 它可能是一个字段,并且该行可以解释为:

fnIndex {}.检查<尺寸> (指数)

在哪里<是小于运算符,>是大于运算符,(索引)是表达式.

使用.template告诉编译器我们要调用模板方法.

猜你在找的C&C++相关文章