gpt4 book ai didi

c++ - 模板 : one for string and one for anything else 中的不同构造函数

转载 作者:行者123 更新时间:2023-11-30 01:48:03 24 4
gpt4 key购买 nike

#include <iostream>
#include <string>
using namespace std;

template <class Type>
class Matrix
{
public:
Type matrix[2][2];

for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if (typeid(matrix[0][0]).name() == typeid(string).name()) {
matrix[i][j] = "0";
}
else {
matrix[i][j] = 0; //this is where I get C2593
}
}
}
}
};

int main()
{
Matrix<string> mString;
Matrix<int> mInt;
.
.
.
return 0;
}

所以,我有这个矩阵模板,如果矩阵的类型是字符串,我想用 "0" 初始化它。否则,我想用 0 进行初始化。我在这里试过这个东西,但得到了一个 error C2593: 'operator =' is ambiguous。有什么我可以做的,或者我的方法是完全错误的吗?

最佳答案

这最终取决于 Matrixintstring 之间有多少不同。

如果您要处理的只是初始默认值,最简单的解决方案可能是外包给辅助函数:

template <class Type>
class Matrix
{
Matrix() {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
setDefault(matrix[i][j]);
}
}
}

// ...

template <typename U>
void setDefault(U& u) { u = 0; }

void setDefault(std::string& u) { u = "0"; }
};

如果您正在做更复杂的事情,那么您可能想要明确地专门化:

template <>
class Matrix<std::string> {
// Matrix of strings
};

关于c++ - 模板 : one for string and one for anything else 中的不同构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30732237/

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