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

标签 c++ class templates

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

我的主要问题是,正确传递模板参数和对象才能使用我的函数。 我的类(class)实现。

//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, 1, MatrixND<double, (Index)1, (Index)0, (Index)0>*, MatrixND<double, (Index)1, (Index)0, (Index)0>*>(MatrixND<double, (Index)1, (Index)0, (Index)0>*&, MatrixND<double, (Index)1, (Index)0, (Index)0>*&)’
     contraction<1,1, decltype(matrix1), decltype(matrix1)>(matrix1, matrix1);

最佳答案

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

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, upper, lower, lower>(arrayc);

因为您实际上并不需要一个指向 MatrixND 的指针,而是一个实际的 MatrixND 对象。

关于c++ - 如何将使用参数包和类型名的类作为函数的输入参数(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58695612/

相关文章:

c++ - 我在使用 std::stack 从递归函数中检索值时遇到问题

c++ - 继承重载成员函数指针的非类型模板形参

c++ - 表达式未计算为常量 - 使用另一个类中的常量

c++ - 在没有成员变量的类上 move 构造函数与复制构造函数行为

java - 使用来自 C++ 的 java 套接字接收 float

c++ - CFLocaleCopy当前陈旧值

python - __iter__ 方法的主体有什么意义?

带有setter getter的Java字符串数组

c++ - 帮助模板特化

javascript - flatiron.js/plates - 如何使用模板和 i18n?