开发者

using template classes as method parameters

I've two template classes: Class1< S > and Class2< T >. In Class2< T >, there's a method that has as parameter a pointer t开发者_如何学运维o an object of Class1< S >. Should I then re-define class2< T > to class2< S, T >? or is there any other best solution? The problem, is that I might have new methods referring to objects of other template classes as parameters. Therefore, I would to avoid having sth. like: 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:
        ...
};


The type of object that Class2::doSomething acts upon should not have to be part of Class2's type. So make Class2::doSomething() a Member Function Template:

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

EDIT:

Defining the member function template is easy enough if you do it inline, but sometimes you can't or don't want to do that, and then some funky syntax comes in to play. Here's a complete example that illustrates both how to define the member function template, and how to call it. I've changed the names to be a little easier to read & follow.

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜