C ++如何使用模板类调用模板函数?

时间:2014-11-27 07:55:08

标签: c++ templates

我对我的程序有一个简单的问题:如何使用Set而不是int调用此模板函数? 我这里有一个名为Set

的课程
#include <iostream>
#include <vector>

using namespace std;

template<typename T> 
class Set
{
public:
    class Iterator;
    void add(T v);
    void remove(T v);
    Iterator begin();
    Iterator end();

private:
    vector<T> data;
}; 

这是我的cpp:
不幸的是,main不能是模板函数,所以我不得不创建另一个函数addstuff,主要调用

template <class T>
Set<T> addstuff()
{
    Set<T> a;
    a.add(1);
    a.add(2);
    a.add(3);
    a.add("a string");

    return a;
}

void main()
{
    addstuff<Set>(); //<< Error here. If I use addstuff<int>(), it would run but   
                     //I can't add string to it. I am required to be able to add 
                     //different data types to this vector
}

1 个答案:

答案 0 :(得分:5)

您的写作addstuff<Set>()将尝试解决Set<Set> addstuff()毫无意义的问题。

addstuff<std::string>() 允许您将std::string添加到您的集合中,但是a.add(1)会失败,因为文字无法隐式转换为字符串类型

addstuff<int>() 确实工作,但这是一个快乐的巧合。 add(1)在该实例中具有正确的类型,以添加到Set<int>

可以构建一个类Foo,它具有字符串和整数的非显式构造函数,并使其成为您的模板类型:addstuff<Foo>()。但是,我不相信你的教授想要你做什么,并且有更好的方法来解决这个问题(一种类型的擦除,但这已经非常复杂)。

相关问题