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

标签 c++ templates c++11 c++14

我有以下代码,问题是当我尝试将 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/

相关文章:

c++ - 使用 "if constexpr"和 SFINAE 禁用分支

c++ - Cygwin使用libwebrtc-audio-processing-devel编译程序

c++ - 如何访问可变模板参数包成员中存在的内部模板 typedef?

C++ 在为 "new"类型专门化模板时如何预定义构造函数参数

C++ 找不到包含

c++ - 使用 vector 的 vector 在 opengl 中绘制地面

c++ - 连接到网络的所有设备的列表

c++ - 无休止的While循环会占用CPU资源吗?

php - 将文本字符串附加到 WooCommerce 产品标题

c++ - 可以基于范围的 C++11 执行/检查额外的操作/条件吗?