【发布时间】:2017-07-17 16:45:43
【问题描述】:
我想弄清楚为什么在编译时会出现问题
#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>。
这是怎么回事?
【问题讨论】:
标签: c++ templates overloading