C++模板错误:"invalid explicitly-specified argument for template parameter"

C++ templating error: "invalid explicitly-specified argument for template parameter"

本文关键字:argument for template parameter explicitly-specified invalid 错误 C++      更新时间:2023-10-16

我有几千行代码正在尝试重构,我可以通过将几个不同的类组合到一个类中来减少大量代码重复,该类通过调用指向外部友元类的指针来处理事情。

我遇到了一个问题,因为我有一个变量num_var,它计算要在计算中使用的许多变量,并且这取决于外部友元类。 这个数字决定了我的许多数组的大小。 对于数组,我经常使用外部函数执行线性代数,这些函数是模板函数,模板参数是数组的大小,num_var. 我曾经有过这种static,但我不再能够这样做了。

我现在收到这样的错误:

candidate template ignored: invalid explicitly-specified argument for template parameter

下面是一个非常简单的程序,它为一个更简单的系统重新复制了编译器错误:

#include <iostream>
enum Color {red=0, blue, green};
class Side {//the side of a shape, which can be a color
public:
Color color;
friend class Shape;
};
//this function adds numerical value of side colors and prints a value
template <size_t N> int sideNamer(Side sides[N]){
int count = 0;
for(int i=0; i<N; i++) count += sides[i].color;
std::cout << "My sides add to " << count << "n";
return count;
};
class Shape { //can have an arbitrary number of sides, each a different color
public:
const int Nsides;
Side *sides;
//constructor sets the number of sides and gives a color to each side
Shape(int N, Color *colors) : Nsides(N){
sides = new Side[Nsides];
for(int i=0; i<Nsides; i++) sides[i].color = colors[i];
};
~Shape(){ delete[] sides;};
//name the sum of the sides
void nameMySides(){
sideNamer<Nsides>(sides);
}
};
int main(){
//make a triangle: should add to 3
Color myTriangleColors[3] = {red, blue, green};
Shape myTriangle(3, myTriangleColors);
myTriangle.nameMySides();
//make a square: should add to 2
Color mySquareColors[4] = {red, red, blue, blue};
Shape mySquare(4, mySquareColors);
mySquare.nameMySides();
}

这给了我同样的错误,关于模板参数的显式指定参数无效。

当我将Shape的声明更改为模板类时,如

template <size_t N> class Shape {
public:
static const int Nsides = N;
Side *sides;
Shape(Color *colors) {
sides = new Side[Nsides];
for(int i=0; i<Nsides; i++) sides[i].color = colors[i];
};
~Shape(){ delete[] sides;};
void nameMySides(){
sideNamer<Nsides>(sides);
}
};

穆坦多比照然后没有问题,它有效。 可悲的是,我无法在我的实际程序中执行此操作,因为在代码中的其他地方,我有另一个类,其中包含指向"Shape"对象的指针数组,并且我无法在代码中的该点指定"size_t",所以我不能在那里使用模板。

我还能做些什么来使模板函数工作吗? 此外,如果允许我将Side数组声明为Side sides[Nsides]而不是Side *sides,也将不胜感激。

当我无法使用模板类static const时,如何使用模板参数? 或者有没有办法使模板类在程序的早期部分工作? 我只需要重写线性代数函数吗?

提前谢谢。

(PS 我处理这个问题的实际类称为Mode,表示物理问题中的特征模态。 它有一个指向一个名为ModeDriver的抽象类的指针,ModeDriver的单个子类可能有 2、4、8、...变量,其数量存储在名为num_var的变量中。 这根据正在建模的特定波形的物理特性而变化。 代码中的几个不同位置使用线性代数函数。

我不相信,也不记得确切的标准术语,const int Nsides;是模板实例化的有效参数。这就是编译器试图告诉您的内容,以及您将其作为模板本身所做的更改所修复的内容。

相关文章: