c++ - 将模板添加到类中,该类在多集中使用

标签 c++ list function templates

解决这个问题的方法可能非常简单,但我找不到答案。一个答案将得到我的感谢和我的眼泪。

基本上,下面的代码在没有模板的情况下也能正常工作(当然使用 T 作为原语),但是一旦我添加了模板,它就会说我的参数列表丢失了。我认为这与声明有关,但这些函数没有使用范围解析,至少不是以我熟悉的方式。我如何让它发挥作用?

template<class T>
class Foo
{
public:
    Foo(T s, int i) : Data(s), pri(i) {}

    //Overload the relational operator so that the priority is compared.
    bool operator < (const Foo<T>& n) const { return n.pri < pri; }
    T getData() { return Data; }
    int getId() { return pri; }

private:
    T Data;
    int pri;
};

这是主要的

int main(void)
{
    set<Foo> s; //These should actually be multiset, but was trying to get it to
    s.insert(Foo("C++", 9)); //work as a set before jumping to multiset
    s.insert(Foo("Is ", 7));
    s.insert(Foo("Fun ", 3));

    set<Foo>::iterator p;
    for (p = s.begin(); p != s.end(); p++)
    {
        Foo n = *p;
        cout << "Id: " << n.getId() << "\t Data: " << n.getData() << endl;
    }

    return 0;
}

如果你很好奇,这个程序应该接受一个字符串(或其他类型)和一个优先级并对优先级进行排序,这个程序还不完整,但我应该在我的程序中使用这个类,但我在将其转换为模板时遇到了麻烦。

最佳答案

std::set期待一个类型

在介绍模板部分之前,Foo是一种类型。

现在这是一个模板类,Foo不再是一种类型。 Foo<int>是一种类型; Foo<std::string>是一种类型;不是Foo .

所以

std::set<Foo<int>> s;

可以工作,

std::set<Foo> s;

报错。

关于c++ - 将模板添加到类中,该类在多集中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44090117/

相关文章:

c++ - 如何在 64 位 Ubuntu 18.04 上使用 64 位 clang v8 构建 32 位 libc++?

C++ 检查项目是否在数组中

python - 在python中将整数列表转换为二进制 "string"

c++ - 如何在递归函数中将字符串捕获到变量中?

c++ - 遍历链表C++并返回用户输入的最高值

c++ - ROS 的 libtiff4 错误

c# - 如果 List<T> 的大小已知,是否值得初始化它的集合大小?

python - 如何在 python 排序(列表)中指定 2 个键?

python - 尝试掌握递归函数

c++ - 使用 std::bind 从 BinaryPredicate 创建 UnaryPredicate 以在 std::transform 中使用