C++:模板:部分特化:打印所有模板

标签 c++ templates partial-specialization

大家好!

具有以下代码:

template<typename T, typename OutStream = std::ostream>
struct print
{
    OutStream &operator()(T const &toPrint, OutStream &outStream = std::cout) const
    {
        outStream << toPrint;
        return outStream;
    }
};

template<typename T, typename Index = unsigned int, typename CharType = char, typename OutStream = std::ostream>
struct print<T *, Index>
{
    print(CharType delimiter = ' '): delimiter_(delimiter) {}
    OutStream &operator()(T const *toPrint, Index startIndex, Index finishIndex, OutStream &outStream = std::cout) const
    {
        for (Index i(startIndex) ; i < finishIndex ; ++i)
            outStream << toPrint[i] << delimiter_;
        return outStream;
    }
protected:
    CharType delimiter_;
};

编译器:MSVCPP10

编译器输出:

1>main.cpp(31): error C2764: 'CharType' : template parameter not used or deducible in partial specialization 'print<T*,Index>'
1>main.cpp(31): error C2764: 'OutStream' : template parameter not used or deducible in partial specialization 'print<T*,Index>'
1>main.cpp(31): error C2756: 'print<T*,Index>' : default arguments not allowed on a partial specialization

我卡住了。帮助我完成部分特化。

谢谢!

最佳答案

我想这就是你的意思:(这可能是不正确的代码,我只是想翻译你写的)

template<typename T> struct print<T*, unsigned int> {
  typedef unsigned int Index;
  typedef std::ostream OutStream;
  typedef char CharType;
  print(CharType delimiter = ' '): delimiter_(delimiter) {}
  OutStream &operator()(T const *toPrint, Index startIndex, Index finishIndex, OutStream &outStream = std::cout) const {
    for (Index i(startIndex) ; i < finishIndex ; ++i)
      outStream << toPrint[i] << delimiter_;
    return outStream;
  }
protected:
  CharType delimiter_;
};

编译器解释出了什么问题:

default arguments not allowed on a partial specialization

意思是 typename Index = unsigned int只能出现在非特化模板中。

template parameter not used or deducible in partial specialization

意味着您必须使用这部分中的所有参数:struct print<HERE>

关于C++:模板:部分特化:打印所有模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9152337/

相关文章:

c++ - 不使用指针的三星bada开发

c++ - 每当采用给定的 SFINAE 构造函数时,定义一个派生自 true_type 的结构

c++ - 具有两个整数参数的类的部分特化

c++ - 根据值的概率从 Map 中获取随机键

c++ - Microsoft Access ODBC 驱动程序管理器函数序列错误

c++ - 是否可以在固定 namespace 下解析模板类型?

c++ - 是否有可能从 "respecialize"派生一个类型派生自专门化类型的专门化类?

c++ - 继承的部分特化。我可以避免继承吗?

c++ - 指针作为模板参数?

c++ - 使用多色 GDI C++ 绘制线条