【发布时间】:2015-02-10 05:49:25
【问题描述】:
我想将仅在编译期间已知的类型的向量传递给一个函数,该函数将其传递给其他函数(根据向量的类型推送元素)。
应该怎么做才能保证编译器不抛出错误:
test.cpp:在 'void funcPushInt(std::vector) [with C = classB]' 的实例化中: test.cpp:28:20:'void checkType(std::vector) [with A = classB]'需要 test.cpp:53:16:从这里需要 test.cpp:38:3: 错误: 没有匹配函数调用'std::vector::push_back(int&)' vec.push_back(i); ^
#include <typeinfo>
#include <vector>
using namespace std;
class classB
{
private:
int i;
public:
B()
{
i = 0;
}
}
template <class A>
void checkType(vector<A>);
template <class C>
void funcPushInt(vector<C>);
template <class B>
void funcPushClassB(vector<B>);
template <class A>
void checkType(vector<A> vec)
{
// check type of vec
if(typeid(vec) == typeid(vector<int>))
funcPushInt(vec);
else if(typeid(vec) == typeid(vector<classB>))
funcPushClassB(vec);
}
template <class C>
void funcPushInt(vector<C> vec)
{
// push int
int i = 1;
vec.push_back(i);
}
template <class B>
void funcPushClassB(vector<B> vec)
{
// error as it can't push float to vector<int>
classB objB;
vec.push_back(objB);
}
int main()
{
// empty vec of classB type
vector<classB> vec;
checkType(vec);
}
【问题讨论】:
-
我更关心所有没有声明返回类型和按值参数的模板函数,在这些函数上,本地更改在返回时对调用者没有任何意义
-
经典 XY 问题。顺便说一句,使用
value_type。 -
你真正想做什么?
-
基本上:1)检查向量的类型 2)根据类型,创建该类型的对象并将其推入
-
如何创建对象?您是否假设它是默认可构造的?