簡體   English   中英

C ++如何使用模板類調用模板函數?

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

我的程序有一個簡單的問題:如何使用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 ,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
}

您編寫的addstuff<Set>()將試圖解決Set<Set> addstuff() ,這是沒有意義的。

addstuff<std::string>() 允許您將std::string添加到您的集合中,但是a.add(1)將失敗,因為無法將文字隱式轉換為字符串類型。

addstuff<int>() 確實有效,但這是一個巧合。 add(1)在該實例中具有要添加到Set<int>的正確類型。

可以構建一個類Foo ,該類具有對字符串和整數的非顯式構造函數,並使其模板類型為: addstuff<Foo>() 但是我不相信這就是您的教授想要您做的,並且有更好的方法來解決此問題(一種類型的擦除,但這已經涉及很多了)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM