Template variable as string instead of const char *

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?

+5
source share
2 answers

"string one" const char*, std::string, . va_arg , :

template <typename VecT, typename EleT>
std::vector<VecT> init_vector(const size_t nargs, EleT first, ...) {
    std::vector<VecT> result;
    result.reserve(nargs);

    if (nargs == 0) {
        return result;
    }

    result.push_back(first);

    if (nargs == 1) {
        return result;
    }

    va_list valist;
    va_start(valist, first);

    for (int i = 1; i < nargs; ++i) {
        result.push_back(VecT(va_arg(valist, EleT)));
    }

    va_end(valist);

    return result;
}

std::vector<std::string> = init_vector<std::string>(2, "string one", "string two")

, , resize reserve, .


( ):

const char *args[] = {"string one" , "string two"};
std::vector<std::string> strvec(args, args + sizeof(args)/sizeof(args[0]))

++ 11:

std::vector<std::string> strvec = {"string one" , "string two"};

, , . . :

template<class C>
inline C init_container() {
    return C();
}

template<class C, class T>
inline C init_container(T arg0) {
    const T args[1] = {arg0};
    return C(args, args + 1);
}

template<class C, class T>
inline C init_container(T arg0, T arg1) {
    const T args[2] = {arg0, arg1};
    return C(args, args + 2);
}

std::vector<std::string> vec =
    init_container< std::vector<std::string> >("hello", "world");

( 100 ) : https://gist.github.com/3419369.

+4

2 :

template <typename T, typename U>
vector<T> initVector(const int argCount, U first, ...) {

(, int, double ..) T U . , , , U T (, const char* string). , , .

BTW - , va_list .. ! OTOH, , ++ 11 , .. , , C, int a[] = { 3, 4, 5 };, .

+1

All Articles