【发布时间】:2012-08-21 19:37:41
【问题描述】:
我喜欢向量,通常在数组上使用它们。出于这个原因,我创建了一个模板化的可变参数函数来初始化向量(包括在下面)。
标题(.h):
template <typename T>
vector<T> initVector(const int argCount, T first, ...);
来源(.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;
}
它适用于大多数类型(例如 int、double...),但不适用于字符串——因为编译器将它们解释为 'const char *',因此
vector<string> strvec = initVector(2, "string one", "string two");
给我错误:
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
有没有什么方法可以将字符串参数解释为字符串,而不必强制转换每个参数?
【问题讨论】:
-
这不是一个很好的解决方案,但也许我可以将“字符串”作为附加参数传递,然后自动转换为每个元素? ://
-
告诉编译器你想要哪种类型而不是依赖演绎是否过于繁琐?以
initVector<std::string>(2,"string 1","string 2")为例。 -
除了您的直接问题之外,将非 POD 类型作为可变参数传递是非法的。
-
@ahenderson:我相信错误消息不是由该行引起的,而是由于模板参数推导试图将类型参数
T适合 2 个不同的类型 调用函数的点. -
@bames53:您是对的,但这只是在将参数传递给函数之前尝试转换为
string的解决方案的问题。如果通过了原始const char*s(如我建议的解决方案),我们仍然很好。