大家好,也许你可以帮我解决这个问题,
我有两个 vector (vecInt、vecDouble)。显然一个是 int 类型,另一个是 double 类型。
但是我如何检查 if 和 else if 中那些 vector 的类型?
if (TYPE OF VECTOR == INT) {
std::cout << "vecInt: ";
}
else if (TYPE OF VECTOR == DOUBLE) {
std::cout << "vecDouble: ";
}
最佳答案
But how do I check the types of those vectors in the if and the else if?
你不知道。这并不是说你不能,只是说你不应该。这种分支不会给你你想要的解决方案,10 次中有 9 次。一个更好的选择是重载。不要添加分支,而是添加对辅助函数的调用,然后重载该辅助函数以获得所需的行为。
看起来像这样:
#include <vector>
#include <iostream>
template<typename T>
void output_helper(std::vector<T>*) {}
void output_helper(std::vector<int>*) {
std::cout << "vecInt: ";
}
void output_helper(std::vector<double>*) {
std::cout << "vecDouble: ";
}
template <typename T>
void output(std::vector<T>* vO) {
output_helper(vO);
for (size_t i = 0; i < vO->size(); i++) {
std::cout << (*vO).at(i) << " ";
}
std::cout << std::endl;
}
int main() {
std::vector<int> v{1, 2, 3};
output(&v);
return 0;
}
确实输出
vecInt: 1 2 3
如你所见live .重载的一个主要好处是您可以扩展 output
的行为而无需修改它。只需为另一种 vector 类型添加重载。
顺便说一句,考虑放弃按指针传递,并按引用传递,就像在惯用的 C++ 中那样。
关于c++ - 如何确定传递给模板函数的 vector 的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47488717/