簡體   English   中英

使用模板類作為方法參數

[英]using template classes as method parameters

我有兩個模板類:Class1 <S>和Class2 <T>。 在Class2 <T>中,有一個方法具有指向Class1 <S>對象的指針作為參數。 然后,我應該將class2 <T>重新定義為class2 <S,T>嗎? 還是有其他最佳解決方案? 問題是,我可能有新方法將其他模板類的對象作為參數引用。 因此,我會避免某事。 像:class2 <S,T,U ...>

template < class S >
class Class1{
    public:
        ...
    private:
        ...
};

template < class T >
class Class2{
    public:
        ...
        Class2<T> * doSomething(Class1<S> * );
        ...
    private:
        ...
};

template < class S, class T >
class Class2{
    public:
        ...
        Class2<T> * doSomething(Class1<S> * );
        ...
    private:
        ...
};

Class2::doSomething作用的對象的類型不必一定是Class2的類型的一部分。 因此,使Class2::doSomething()成為成員函數模板

template < class T >
class Class2{
    public:
        ...
        template<class S> Class2<T> * doSomething(Class1<S> * );
        ...
    private:
        ...
};

編輯:

如果您以內聯方式進行定義,則輕松定義成員函數模板非常容易,但是有時您可能不想這樣做,然后便會使用一些時髦的語法。 這是一個完整的示例,它說明了如何定義成員函數模板以及如何調用它。 我將名稱更改為更易於閱讀和遵循。

template<class FooType> class Foo
{
};

template<class BarType> class Bar
{
public:
    template<class FooType> Bar<BarType>* doSomething(Foo<FooType>* foo);
};

template<typename BarType> template<typename FooType> Bar<BarType>* Bar<BarType>::doSomething(Foo<FooType>* foo)
{
    return 0;
}

int main()
{
    Foo<unsigned> foo_1;
    Bar<double> bar_1;
    Bar<double> * bar_copy = 0;
    bar_copy = bar_1.doSomething<unsigned>(&foo_1);
    return 0;
}

暫無
暫無

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

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