C模板参数推断

C模板参数推断,第1张

概述作为练习我试图使用模板编写数组实现,但使用函数指针作为模板参数.每次对数组进行索引时都会调用此函数. template<typename T, int size>using Array_fnIndex = void (*)(int index);template<typename T, int size, typename Array_fnIndex<T, size> fnIndex>st 作为练习我试图使用模板编写数组实现,但使用函数指针作为模板参数.每次对数组进行索引时都会调用此函数.
template<typename T,int size>using Array_fnIndex = voID (*)(int index);template<typename T,int size,typename Array_fnIndex<T,size> fnIndex>struct Array {    T data[size];    T& operator[](int index) {        fnIndex(index);        return data[index];    }};// example index functiontemplate<typename T,int size>voID checkIndex(int index) {    assert(index < size);}int main() {    Array<int,10,checkIndex<int,10>> a; // this works    Array<int,11>> b; // this also works,not what I want    Array<int,checkIndex> c; // this doesn't work,but what I want    return 0;}

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

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

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

解决方法 可能不适用于您的实际用例,但我建议一个包含执行检查的函数的可调用对象:
template<typename T,typename fnIndex>struct Array {    T data[size];    T& operator[](int index) {        fnIndex{}.template check<size>(index);        return data[index];    }};struct checkIndex {    template<int size>    voID check(int index) {        assert(index < size);    }    };int main() {        Array<int,checkIndex> c;    return 0;}

wandbox example

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

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

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

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

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

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

总结

以上是内存溢出为你收集整理的C模板参数推断全部内容,希望文章能够帮你解决C模板参数推断所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1238283.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存