如何将使用参数包和类型名的类作为函数的输入参数(C ++)

我创建了一个类,该类带有一个typename模板变量和一个parameter pack。在下一步中,我希望能够将该类的两个对象传递给我的函数。

我的主要问题是正确传递模板参数和对象以能够使用我的函数。 我的课堂实现。

//auto as template parameter is for non-type parameter(c++17)
template <auto value> constexpr auto DIM = value;
//constexpr on values in header files(c++17)
inline constexpr auto const DIM3 = DIM <3>;
inline constexpr auto const DIM2 = DIM <2>;


enum Index : int {lower = 0,upper = 1};


template<int base,int exponent>
int constexpr pow(){
    if constexpr(exponent == 0){
        return 1;
    }else{
        return base * pow<base,exponent-1>();
    }
}
template<int Size,typename T>
struct Array{
    T array[Size];
    Array(const T * a){
        for(int i = 0; i < Size; i++){
            array[i] = a[i];
        }
    }
};



//auto as template parameter is for non-type parameters(c++17)
template<typename T = double,auto ...Indicesn>
class MatrixND{

private:
    const Array<pow<DIM3,sizeof...(Indicesn)>(),T> matrix;

public:
    MatrixND(const T * arr): matrix(arr){}

    template<auto ...args>
    auto constexpr getElement(){
    }
};

采用MatrixND对象的函数:

template<auto posT1,auto posT2,typename A,typename B>
auto constexpr function(const MatrixND<A> tensor1,const MatrixND<B> tensor2){

    return 0;
}

我尝试了以下操作,但是它抛出一条错误消息“没有匹配的函数调用”:

const double arrayc[27] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27};
auto matrix1 = new MatrixND<double,upper,lower,lower>(arrayc);

function<1,1,decltype(matrix1),decltype(matrix1)>(matrix1,matrix1);

错误消息:

error: no matching function for call to ‘function<1,MatrixND<double,(Index)1,(Index)0,(Index)0>*,(Index)0>*>(MatrixND<double,(Index)0>*&,(Index)0>*&)’
     contraction<1,matrix1);
merkava_yue 回答:如何将使用参数包和类型名的类作为函数的输入参数(C ++)

您需要将参数包添加到function的模板参数中。使用

template<auto posT1,auto posT2,typename A,typename B,auto ...AIndicesN,auto ...BIndicesN>
auto constexpr function(const MatrixND<A,AIndicesN...> tensor1,const MatrixND<B,BIndicesN...> tensor2){

    return 0;
}

允许您调用

之类的函数
auto foo = function<1,1>(matrix1,matrix1);

请注意,要将此代码与您的代码一起编译,您需要进行更改

auto matrix1 = new MatrixND<double,upper,lower,lower>(arrayc);

auto matrix1 = MatrixND<double,lower>(arrayc);

因为您实际上并不想要指向MatrixND的指针,而是真正的MatrixND对象。

,

将函数调用为

function<1,1,decltype(matrix1),decltype(matrix1)>(matrix1,matrix1);

您说模板参数ABdecltype(matrix1),这意味着它们实际上是MatrixND<double,lower>

反过来意味着例如参数tensor1的类型为const MatrixND<MatrixND<double,lower>>。那不是你所通过的。

可能的解决方案是在参数列表中不要使用MatrixND<A>(和MatrixND<B>),而只能使用

template<auto posT1,typename B>
auto constexpr function(const A tensor1,const B tensor2){

    return 0;
}

您可能还应该传递引用而不是值作为参数。


如果您像上面那样使用该函数,那么您也不需要AB类型的模板参数,这是由编译器推论得出的:

function<1,matrix1);
本文链接:https://www.f2er.com/3165939.html

大家都在问