gpt4 book ai didi

c++ - 模板化类参数重载

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:41 27 4
gpt4 key购买 nike

我正在努力思考为什么在编译时会出现问题

#include <iostream>
template <unsigned int ROWS,unsigned int COLS>
class Matrix{
public:
double dotProd(const Matrix<1,COLS>& other){
static_assert(ROWS==1,"dotProd only valid for two vectors");
return COLS;//place holder for dot product with row vectors
}
double dotProd(const Matrix<ROWS,1>& other){
static_assert(COLS==1,"dotProd only valid for two vectors");
return ROWS;//place holder for dot product with col vectors
}
};
int main(){
Matrix<1,32> bob;
Matrix<1,32> fred;
std::cout<<bob.dotProd(fred)<<std::endl;
return 0;
}

这是给我这个错误:

overloadedTemplateMethod2.cpp: In instantiation of ‘class Matrix<1u, 1u>’:
overloadedTemplateMethod2.cpp:17:32: required from here
overloadedTemplateMethod2.cpp:9:16: error: ‘double Matrix<ROWS,COLS>::dotProd(const Matrix<ROWS, 1u>&) [with unsigned int ROWS = 1u; unsigned int COLS = 1u]’ cannot be overloaded
double dotProd(const Matrix<ROWS,1>& other){
^
overloadedTemplateMethod2.cpp:5:16: error: with ‘double Matrix<ROWS, COLS>::dotProd(const Matrix<1u, COLS>&) [with unsigned int ROWS = 1u; unsigned int COLS = 1u]’
double dotProd(const Matrix<1,COLS>& other){
^

我知道填写参数的模板会导致第二个函数解析为 double dotProd(const Matrix<1,1>& other)但我认为另一个应该解决 double dotProd(const Matrix<1,32>& other) , 不是 Matrix<1,1>再次。

这是怎么回事?

最佳答案

当你这样做时:

bob.dotProd(fred)

dotProd函数被实例化以解决对 Matrix<1,32> 的调用.
我们可以这样说(免责声明:这并不完全是它的工作原理,但它给出了幕后发生的事情的想法)它们最终被声明为:

double dotProd(const Matrix<1,32>& other);
double dotProd(const Matrix<1,1>& other);

忽略第一个,让我们专注于第二个。它需要一个新的专业 Matrix ,即:Matrix<1,1> .
如果您考虑这样的特化,您将获得哪些关于 dotProd 的声明?如果用实际值替换模板参数?

double dotProd(const Matrix<1,1>& other); // Matrix<1, COLS>
double dotProd(const Matrix<1,1>& other); // Matrix<ROWS, 1>

也就是说,您最终声明了一个参数列表没有区别的重载函数。因此错误。

如果替换 main 的正文,您会得到完全相同的错误。使用以下行函数:

 Matrix<1,1> someone;

换句话说,你的类模板MatrixCOLS 的情况下是错误的和 ROWS是平等的。

关于c++ - 模板化类参数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45149560/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com