【问题标题】:Specialization of a class template method, with typenames that are class template - error: type/value mismatch at argument类模板方法的特化,类型名是类模板 - 错误:参数的类型/值不匹配
【发布时间】:2018-04-04 21:19:52
【问题描述】:

我的问题是,当模板是另一个模板的参数时,我是否必须指定模板的“类型”?这是一种方法的特化。

允许我把你放在上下文中。

我正在做一个井字游戏,其中有一个模板计算机类。所以,我可以在参数中设置它的难度级别。 这是它的一个样本:

template<int T>
class Computer
{
    Node *Root;         /**< Root of a decision tree */
    Node *Current;      /**< Current node in a decision tree*/

    int PlayerNumber;   /**< Player ID*/
    int OponnentNumber  /**< Opponent ID*/

  Public:

    /**< Constructor destructor */
    int refreshBoard(int move);
    int play()const; /**< This methods has different implementations, for each level of difficulty*/
}

然后,我想出了一个想法,创建一个 TicTacToe 模板类,以便参数接收不同类型的玩家。 这是一个示例。

template <typename T1, typename T2>
class TicTacToe
{
    T1 &Player1;        /**< Simulates the first player */
    T2 &Player2;        /**< Simulates the second player */

     Board &b__;        /**< Simulates a board */

     int TurnCounter; 
 public:
    int newTurn(); 
 /* This method is implemented differently for each type of combination of player
  * Lets say player 1 is Human and player 2 is computer. The new turn will 
  * change the state of the board and will return 1 if there is still new turns 
  * to come.
  */
}

回到我的问题:我在设置正确的语法时遇到问题,所以编译器理解我。

它返回很多错误:

error: type/value mismatch at argument 2 in template parameter list for ‘template<class T1, class T2> class TicTacToe’
 int JogoVelha<Human,Computer>::newTurn()`


note: expected a type, got ‘Computer’
header/TicTacToe.h:201:40: error: ‘newTurn’ is not a template function
 int TicTacToe<Human,Computer>::newTurn()

对于这种类型的组织

template<>
int TicTacToe<Human,Computer>::newTurn() 
...implementation

我不明白为什么。我需要你的帮助。

【问题讨论】:

  • 我认为这只是为了实验目的?因为否则我并没有真正看到在这里使用模板比仅使用由 HumanPlayer 和 ComputerPlayer 类实现的 Player 接口的优势......
  • 这是我开始时的一个项目决定。后来我注意到这不是最好的选择。但是,您的想法并没有出现在我的脑海中,并且它更直接,更简单,然后是我想出的。如果您不介意,我将使用您所说的内容来构建我的战舰项目

标签: c++ class templates template-specialization


【解决方案1】:

Computer是类模板,使用时必须指定模板参数,例如

template<>
int TicTacToe<Human,  Computer<42>>::newTurn()

或者你可以partial specify TicTacToe 为类模板,如Computer,它采用int 模板参数。 .例如

template <typename T1, template <int> class T2, int I>
class TicTacToe<T1, T2<I>>

{
    T1 &Player1;        
    T2<I> &Player2;
    ...
};

然后像这样使用它

TicTacToe<int, Computer<42>> t;

LIVE

【讨论】:

  • 那么,第一个建议将迫使我进行20种专业化,如果有20种难度级别,尽管在井字游戏中的实现角度是相同的?没有像 void 指针或更通用的选项吗?
  • @Homunculus 答案已修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多