c++ - 如何确定传递给模板函数的 vector 的类型

标签 c++ templates

大家好,也许你可以帮我解决这个问题,

我有两个 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/

相关文章:

c++ - 为什么可以在没有类实例的情况下在编译时访问非常量、非静态成员?

c++ - 如何处理模板化代码中的变量const?

c++ - 无法声明变量 Char[]

c++ - dlsym()/dlopen() 的用法

c++ - 从类内部创建一个信号来调用外部函数?

c++ - 关于 Struct 上的 new 和 delete 运算符

c++ - 要将嵌套类中定义的静态模板函数声明为兄弟嵌套类中的友元,必须做什么?

c++ - 错误 C4430 : missing type specifier - int assumed. 注意:C++ 不支持我的构造函数的默认整数

c++ - 如何创建一个类,使 vector 起作用std::vector <MyClass <int >> v {1,2,3};

c++ - 运行代码时是否有可能在 main() 之前调用其他方法/指令