gpt4 book ai didi

C++ 将模板类型作为参数传递给错误

转载 作者:行者123 更新时间:2023-11-28 02:30:25 24 4
gpt4 key购买 nike

我有以下代码,问题是当我尝试将 basic_string 类型传递给 writeContainer 函数时它给我错误,它将类型 Cont 读取为 std::_String_val< std::_Simple_types > 所以它给我错误,比如没有 size() 方法,并且每个循环都没有 end() 或 begin() 方法。

很棒的是,当我使用 vector 时它工作正常,即使它们是相同的概念!!任何帮助表示赞赏

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 本身实现)。

尽管你的说法与此相反,但我得到了一个 similar error当使用 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++ 将模板类型作为参数传递给错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29154257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com