im dumb
im dumb

Reputation: 151

C++ How can I call a template function with a template class?

I have a quick question for my program: How can I call this template function with Set, rather than int? I have a class here called 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;
}; 

Here's my cpp:
Unfortunately, main cannot be a template function so I had to make another function addstuff, which main calls

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
}

Upvotes: 0

Views: 202

Answers (1)

Bathsheba
Bathsheba

Reputation: 234705

Your writing addstuff<Set>() would be an attempt to resolve to Set<Set> addstuff() which is meaningless.

addstuff<std::string>() would allow you to add std::strings to your set, but then a.add(1) would fail since the literal cannot be implicitly converted to a string type.

addstuff<int>() does work but that's a merry coincidence. add(1) has the correct type in that instance to be added to Set<int>.

You could build a class Foo that has non-explicit constructors to a string and an integer and make that your template type: addstuff<Foo>(). But I'm not convinced that's what your professor wants you to do and there are better ways of solving this (type erasure for one, but this is getting quite involved).

Upvotes: 5

Related Questions