2014-03-25 46 views
1

的成员函数我是新来的C++和Im学习使用模板。 我想使模板类与2个模板参数,并且从类专门的单个成员函数,对于其中所述第二模板参数是模板上的指针类型的第一个参数的矢量的情况。我想的是我的尝试会更加清楚的例子:C++专门为载体

//Container.h: 

template<class T , class CONT > 
class Container { 

private: 
    CONT container; 
    T someData; 
public: 
    void foo(); 
}; 

,我尝试了特化了的std ::向量是:

//Container.cpp 

template<class T> 
void Container<T, std::vector<T*> > ::foo(){ 
    cout << "specialized foo: " << container.pop_back(); 
    } 

template<class T, class CONT > 
void Container<T, CONT > ::foo(){ 
    cout << "regular foo: " << container.pop_back()); 
} 

,但我得到这些erors:

error C3860: template argument list following class template name must list parameters in the order used in template parameter list 
error C2976: 'Container<T,CONT>' : too few template argument 

Container类的使用必须是该第一参数是某种类型的,并且第二个是一个STL容器,载体或列表。例如:

Container<int, vector<int*> > c; 
c.foo(); 

我是什么东错了?

+3

除了语法错误,你不能专注函数模板部分,所以这种方法不工作。 –

回答

1

正确语法类模板来定义成员函数是

template<class T, class CONT > 
void Container<T, CONT>::foo() 
{ 
    cout << "specialized foo:" ; 
} 

FOO()函数未过载和重新定义。重新定义foo()函数也会给出错误。您不能在返回类型的基础上重载函数。 std :: vector的特化不正确。 < <运营商也应该重载你can'y直接使用这样

cout << container.pop_back();

+0

我编辑了语法错误,除此之外,你可以假定operator <<重载,我只是想表明foo使用容器对象的成员函数。 – user3066442

1

您可以使用基于策略的设计。现在有这个许多变化,但一个简单的例子是这样这样

#include <iostream> 
#include <vector> 

using namespace std; 

template<typename T, class CONT> 
struct foo_policy { 
    static inline void execute() { 
     cout << "regular foo: \n" ; 
    } 
}; 

template<typename T> 
struct foo_policy<T, std::vector<T*>> { 
    static inline void execute() { 
     cout << "specialized foo: \n" ; 
    } 
}; 

template<class T , class CONT > 
class Container 
{ 
private: 
    CONT container; 
    T someData; 
public: 
    void foo() 
    { 
     foo_policy<T, CONT>::execute(); 
    } 
}; 

int main() 
{ 
    Container<int, std::vector<int>> a; 
    Container<int, std::vector<int*>> b; 
    a.foo(); 
    b.foo(); 
    return 0; 
} 

Here's a demo。在另一种情况下,你可以从foo_policy类派生容器和使用基本成员的功能(但有更多的复杂影响)

+0

谢谢,我想它会完成这项工作,但我认为有一个更直接的方法来实现这一目标。 – user3066442