使用模板类作为方法参数

时间:2010-11-15 23:09:12

标签: c++ templates parameter-passing

我有两个模板类: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:
        ...
};

1 个答案:

答案 0 :(得分:5)

Class2::doSomething作用的对象类型不应该是Class2类型的一部分。因此,将Class2::doSomething()设为Member Function Template

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