2012-10-03 45 views
2

我在头文件中使用模板。我使用的函数是递归的,我想保留函数外的两个变量进行比较。这里是我的代码(注意:不能编译):C++头文件模板

#include "Position.h" 
#ifndef _SOLVER_H 
#define _SOLVER_H 

class Solver{ 
    public: 
    template<typename T> 
    int EvaluatePosition(T &p, bool me) { 
     int score = 0; 
     if(p.isGameOver()) { 
      return p.score(me); 
     } 
     else { 
      std::vector<T> nextMoves = p.getNextPositions(); 
      for(int i=0; i != nextMoves.size(); i++) { 
       score += EvaluatePosition(nextMoves[i],!me); 
       if(score > maxScore) { 
        p.display(); 
        maxScore = score; 
        maxP = p; 
        p.display(); 
       } 
      } 
      return score; 
     } 
    } 

    T maxP; // Want this to be the same Type T that is used in the function 
    int maxScore; 
}; 

#endif 

我试图创建函数中使用相同的通用类型的T的一个变量,这样我可以节省出一些数据。这是可能的,如果是的话,它将如何完成?

回答

2

您可以让整个班级成为模板化的班级,而不仅仅是功能。

template< class T > class Solver{ 
    //here goes your function that takes the argument of T class 
    int EvaluatePosition(T &p, bool me){ 
     //... 
    } 

    T maxP; //here goes your variable 
    int maxScore; 
}; 
+0

这会影响呼叫站点(类型扣除将不再发生)。另外,它不是必需的(请参阅我的答案,找出隐藏实现细节的替代方案) – sehe

0

你当然可以模板整个班级。假设您不喜欢该呼叫接口,您可以使用本地模板类来保持该状态:

class Solver{ 
    public: 
    template<typename T> int EvaluatePosition(T &p, bool me) 
    { 
     struct Helper { 
      T maxP; 
      int maxScore; 

      int DoEval(T &p, bool me) 
      { 
       int score = 0; 
       if(p.isGameOver()){ 
        return p.score(me); 
       } 
       else{ 
        std::vector<T> nextMoves = p.getNextPositions(); 
        for(int i=0; i != nextMoves.size(); i++){ 
         score += DoEval(nextMoves[i],!me); 
         if(score > maxScore){ 
          p.display(); 
          maxScore = score; 
          maxP = p; 
          p.display(); 
         } 
        } 
        return score; 
       } 
      } 
     } helper; 

     return helper.DoEval(p, me); 
    } 
};