简体   繁体   English

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

[英]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 ? 我的程序有一个简单的问题:如何使用Set而不是int调用此模板函数? I have a class here called Set 我这里有一个叫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: 这是我的cpp:
Unfortunately, main cannot be a template function so I had to make another function addstuff , which main calls 不幸的是,main不能是模板函数,所以我必须使另一个函数addstuff ,main调用

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
}

Your writing addstuff<Set>() would be an attempt to resolve to Set<Set> addstuff() which is meaningless. 您编写的addstuff<Set>()将试图解决Set<Set> addstuff() ,这是没有意义的。

addstuff<std::string>() would allow you to add std::string s to your set, but then a.add(1) would fail since the literal cannot be implicitly converted to a string type. addstuff<std::string>() 允许您将std::string添加到您的集合中,但是a.add(1)将失败,因为无法将文字隐式转换为字符串类型。

addstuff<int>() does work but that's a merry coincidence. addstuff<int>() 确实有效,但这是一个巧合。 add(1) has the correct type in that instance to be added to Set<int> . add(1)在该实例中具有要添加到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>() . 可以构建一个类Foo ,该类具有对字符串和整数的非显式构造函数,并使其模板类型为: 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). 但是我不相信这就是您的教授想要您做的,并且有更好的方法来解决此问题(一种类型的擦除,但这已经涉及很多了)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM