我对我的程序有一个简单的问题:如何调用此模板函数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;
};
Run Code Online (Sandbox Code Playgroud)
这是我的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
}
Run Code Online (Sandbox Code Playgroud)
你的写作addstuff<Set>()将试图解决Set<Set> addstuff()这个问题毫无意义.
addstuff<std::string>() 将允许您将std::strings 添加到您的集合,但随后a.add(1)将失败,因为文字不能隐式转换为字符串类型.
addstuff<int>() 确实有效,但这是一个快乐的巧合.add(1)在要添加到的实例中具有正确的类型Set<int>.
您可以构建一个Foo具有字符串和整数的非显式构造函数的类,并使其成为您的模板类型:addstuff<Foo>().但我不相信你的教授希望你做的是什么,并且有更好的解决方法(一种类型的擦除,但这已经非常复杂).