gpt4 book ai didi

c++ - C++ 中的模板模板参数

转载 作者:行者123 更新时间:2023-11-30 01:43:48 24 4
gpt4 key购买 nike

#include <vector>
#include <iostream>
#include <string>
using namespace std;

#include <vector>
#include <iostream>
#include <string>
using namespace std;
// Template-template argument must
// be a class; cannot use typename:
template<typename T, template<typename> class C>
void print2(C<T>& c) {
copy(c.begin(), c.end(),
ostream_iterator<T>(cout, " "));
cout << endl;
}
int main() {
vector<string> v(5, "Yow!");
print2(v);
} ///:~

这段代码在我看来非常完美。但是这段代码无法在我的 Mac 中编译。错误信息如下

 note: candidate template ignored: substitution failure [with T = std::__1::basic_string<char>]: template template argument has
different template parameters than its corresponding template template parameter

void print2(C<T>& c) {
^
1 error generated.

最佳答案

这是因为 std::vector 不是单参数模板。标准要求 std::vector 的元素类型和分配器类型参数。

如果您不使用旧版 C++ 并且可以使用可变参数模板,您可以像这样声明您的函数:

template<typename T, template<typename...> class C>
void print2(C<T>& c);

关于c++ - C++ 中的模板模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37196954/

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