gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:10:46 25 4
gpt4 key购买 nike

大家好!

具有以下代码:

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/

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