C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C模板参数推断大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
作为练习我试图使用模板编写数组实现,但使用函数指针作为模板参数.每次对数组进行索引时都会调用函数.
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 function
template<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;
}
@H_677_4@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模板参数推断所遇到的程序开发问题。

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。