C++将模板类型作为参数传递会出错
C++ passing template type as argument gives error
我有以下代码,问题是当我尝试将basic_string类型传递给 writeContainer 函数时,它给了我错误,它将 Cont 类型读取为 std::_String_val<std::_Simple_types> 所以它给了我错误,就像没有 size(( 方法一样,并且每个循环都没有 end(( 或 begin(( 方法。
好消息是,当我使用矢量时,它工作正常,即使它们是相同的概念! 任何帮助表示赞赏
template< template<typename> class Cont, typename T >
void writeContainer(Stream& stream, const Cont<T>& outValue) {
stream << (int32_t)outValue.size();
for (auto& v : outValue) {
stream << v;
}
}
template<typename T>
Stream& operator<<(Stream& stream, const basic_string<T>& outValue) {
writeContainer(stream, outValue);
return stream;
}
我得到的错误,我使用 VS2013
error C2039: 'size' : is not a member of 'std::_String_val<std::_Simple_types<char>>'
see reference to function template instantiation 'void writeContainer<std::_String_val,std::_Simple_types<char>>(Stream &,const std::_String_val<std::_Simple_types<char>> &)' being compiled
see reference to function template instantiation 'Stream &operator <<<char>(Stream &,const std::basic_string<char,std::char_traits<char>,std::allocator<char>> &)' being compiled
error C3312: no callable 'begin' function found for type 'const std::_String_val<std::_Simple_types<char>>'
error C3312: no callable 'end' function found for type 'const std::_String_val<std::_Simple_types<char>>'
error C2065: 'v' : undeclared identifier
对于模板模板参数,参数必须是具有完全相同参数数的类模板 - 计算具有默认值的参数。因此,即使std::vector
可以用一个参数实例化,它也是一个双参数模板(第二个参数具有默认值(,并且不能是Cont
的参数。同样,std::basic_string
是一个三参数模板。
在你的例子中发生的事情是这样的。在这个特定的实现中,std::basic_string
派生自一个名为 _String_val
的内部类,不幸的是,它恰好是一个单参数模板。所以Cont
被推导出为_String_val
,但随后实例化失败,因为_String_val
没有一个名为size
的方法(该方法由basic_string
本身实现(。
尽管您声称相反,但我在使用std::vector
代替std::basic_string
时遇到了类似的错误 - 出于完全相同的原因。
现在,没有理由将Cont
作为模板模板参数(并且有充分的理由不这样做 - 它不起作用(。使其成为普通类型参数,否则让函数采用一对迭代器。大致如下:
template<typename Cont>
void writeContainer(Stream& stream, const Cont& outValue);
// or
template<typename Iter>
void writeRange(Stream& stream, Iter first, Iter last);
相关文章:
- 将私有数据成员作为默认参数传递给该类的公共方法时出错
- 使用模板函数传递模板参数时出错
- 在 c++ 中调用将字符串作为参数传递的函数时出错
- 在运算符中将联合作为参数传递时出错<<
- C++ 在C++中通过引用将枚举作为默认参数传递时出错
- 将非静态函数作为参数传递时出错
- 传递具有依赖嵌套参数类型的模板模板参数时出错
- 将模板参数传递到内部结构时出错
- 将'const'作为参数传递'this'时出错
- C++将模板类型作为参数传递会出错
- 将std::vector作为模板模板参数传递时出错-在GCC中有效,在MSVC中失败
- 将数组作为函数参数传递时出错
- 在C++中将 2d 数组作为函数参数传递时出错
- 使用常量限定符将参数传递到模板函数时出错
- 将常量指针作为参数传递时出错
- 将“const”作为“const double”的“this”参数传递时出错,将丢弃限定符
- 传递std::map作为模板模板参数时出错
- 向函数传递参数时出错
- 将函数指针作为构造函数的参数传递给私有实例变量时出错
- 传递参数时出错,并将其转换为十六进制