C++ 模板专门化,使用 typename 时出错

标签 c++ c++11 templates template-specialization

我需要专门化一个成员函数:

template <typename T>
int32_t writeVectorVariableUnit(
    foo& classFoo,
    typename std::vector<T>::const_iterator& start,
    typename std::vector<T>::const_iterator& stop,
    const std::string& name,
    const std::string& unit,
    const std::string& longName,
    const std::vector<std::string>& dimName) const

这样:

template <>
int32_t writeVectorVariableUnit(
    foo& classFoo,
    std::vector<uint16_t>::const_iterator& start,
    std::vector<uint16_t>::const_iterator& stop,
    const std::string& name,
    const std::string& unit,
    const std::string& longName,
    const std::vector<std::string>& dimName) const;

但是 g++ 编译器(redhat 6.7 上的版本 4.4.7)提示无法匹配任何模板声明:

error: template-id ‘writeVectorVariableUnit<>’ for ‘int32_t writeVectorVariableUnit(foo&, __gnu_cxx::__normal_iterator > >&, __gnu_cxx::__normal_iterator > >&, const std::string&, const std::string&, const std::string&, const std::vector, std::allocator >, std::allocator, std::allocator > > >&) const’ does not match any template declaration

我怀疑这与typename的使用有关,我尝试了几种组合但没有成功。 您有什么建议吗?

最佳答案

这些问题与typename的使用无关。 ,他们是

  1. 您应该将模板从类定义中专门化。

  2. 对于 std::vector<uint16_t>::const_iterator , T不能推导为uint16_t因为这属于non-deduced contexts 。这意味着您必须显式指定专用模板参数。

If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails.

1) The nested-name-specifier (everything to the left of the scope resolution operator ::) of a type that was specified using a qualified-id:

例如

template <>
int32_t bar::writeVectorVariableUnit<uint16_t> (
//      ~~~~~                       ~~~~~~~~~~
    foo& classFoo,
    std::vector<uint16_t>::const_iterator& start,
    std::vector<uint16_t>::const_iterator& stop,
    const std::string& name,
    const std::string& unit,
    const std::string& longName,
    const std::vector<std::string>& dimName) const {
    // ...
}

关于C++ 模板专门化,使用 typename 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41938104/

相关文章:

c++ - 统计数据项时的内联代码(使用模板)

c# - 将 C++ 项目转换为 DLL 以在 C# 应用程序中使用

c++ - 未找到 unordered_map

C++: std::move with rvalue reference 不 move 内容

c++ - 函数作为模板参数

C++静态模板函数导致armcc编译错误(304)

html - 如何在 Bootstrap 中制作这样的表格?

c++ - 将 CMake.txt 转换为 .vcxproj 文件 C++ Visual Studio 项目

c++ - 当我从 int 切换到 double 时,数组中出现奇怪的反馈

c++ - 原始循环与依赖于索引的循环算法