【发布时间】:2020-05-21 17:21:52
【问题描述】:
我需要用 C++ 编写一个实现集合的抽象版本的模板。我找不到关于编译错误的解决方案(或者更糟的是,我真的不明白该怎么做)。
这是我需要编译和运行的主程序的简化版本——也就是说,我不能更改其中的任何内容:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <set>
#include <string>
#include "testset.h"
using namespace std;
struct string_size_less
{
bool operator()( const std::string& a,
const std::string& b )
{
return a.size() < b.size();
}
};
int main()
{
std::set<std::string> msgs;
msgs.insert("One");
msgs.insert("Two");
msgs.insert("Three");
set_ops<std::string> ops(msgs);
ops.list();
std::set<std::string, string_size_less> x;
x.insert("Hello");
x.insert("Ciao");
std::set<std::string, std::greater<std::string> > a;
a.insert(":-o");
set_ops<std::string> m(x);
m.list();
return 0;
}
我需要编写“set_ops”类(在 testset.h 中)。我剥离了所有不相关的部分(否则有效):
#pragma once
#include <iostream>
#include <set>
using namespace std;
template <class T> class set_ops
{
private:
std::set<T> elements;
public:
set_ops(std::set<T> initialSet)
{
elements = initialSet;
}
void list() const;
};
template <class T> void set_ops<T>::list() const
{
for (typename set<T>::iterator i = elements.begin(); i != elements.end(); ++i) {
cout << "\t" << *i << endl;
}
}
当我尝试编译它时,我得到了错误:
In function 'int main()':
error: no matching function for call to 'set_ops<std::__cxx11::basic_string<char> >::set_ops(std::set<std::__cxx11::basic_string<char>, string_size_less>&)'
note: candidate: set_ops<T>::set_ops(std::set<T>) [with T = std::__cxx11::basic_string<char>]|
note: no known conversion for argument 1 from 'std::set<std::__cxx11::basic_string<char>, string_size_less>' to 'std::set<std::__cxx11::basic_string<char> >'
我尝试了很多东西并试图找到一个很好的例子等,但到目前为止还没有找到。例如,我知道(并尝试过)如果我添加另一个像这样的模板参数:
template <class T, class U = std::less<T> > class set_ops
{
private:
std::set<T, U> elements;
public:
set_ops(std::set<T, U> initialSet)
{
elements = initialSet;
}
void list() const;
};
template <class T, class U> void set_ops<T, U>::list() const
{
for (typename set<T, U>::iterator i = elements.begin(); i != elements.end(); ++i) {
cout << "\t" << *i << endl;
}
}
那么如果我明确写:
set_ops<std::string, string_size_less> m(x);
它编译并运行没有错误。但是,同样,我不能更改 main() 中的任何内容,所以这不是一个选项。
如果我保留原始 main() 中的行,即使更改了 testset.h,我也会得到相同的编译错误。
如果有人可以提供帮助,我真的很想了解这里的问题(希望是解决方案)。谢谢!
【问题讨论】:
-
AFAIK 如果不更改
main,这是无法做到的。 -
@NathanOliver 确实可以通过滥用多态性来实现。
-
是否指定了输出?否则您可以复制内容并更改顺序。