I want to pass a vector of type that is only known during compile time to a function which will pass it to other functions (to push elements depending on the type of vector).
How should i do it to ensure that the compiler does not throw the error:
test.cpp: In instantiation of 'void funcPushInt(std::vector) [with C = classB]': test.cpp:28:20: required from 'void checkType(std::vector) [with A = classB]' test.cpp:53:16: required from here test.cpp:38:3: error: no matching function for call to '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);
}
value_type.