I like vectors and usually use them in arrays. For this reason, I created a template variational function for initializing vectors (see below).
Title (.h):
template <typename T>
vector<T> initVector(const int argCount, T first, ...);
Source (.hpp):
template <typename T>
vector<T> initVector(const int argCount, T first, ...) {
vector<T> retVec;
retVec.resize(argCount);
if(argCount < 1) { ... }
retVec[0] = first;
va_list valist;
va_start(valist, first);
for(int i = 0; i < argCount-1; i++) { retVec[i+1] = va_arg(valist, T); }
va_end(valist);
return retVec;
}
It works fine for most types (like int, double ...), but not for strings --- since the compiler interprets them as "const char *", thus
vector<string> strvec = initVector(2, "string one", "string two");
gives me an error:
error: conversion from ‘std::vector<const char*, std::allocator<const char*> >’ to non-scalar type ‘std::vector<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::allocator<std::basic_string<char, std::char_traits<char>, std::allocator<char> > > >’ requested
Is there a way to make string arguments be interpreted as strings without having to throw them?
source
share