user180574 user180574 - 3 months ago 8
C++ Question

not able to compile code with "std::pair"

I try to study and modify this program "https://github.com/PetterS/monte-carlo-tree-search.git" like this.

diff --git a/games/connect_four.h b/games/connect_four.h
index a575217..52f59cf 100644
--- a/games/connect_four.h
+++ b/games/connect_four.h
@@ -3,6 +3,7 @@

#include <algorithm>
#include <iostream>
+#include <utility>
using namespace std;

#include <mcts.h>
@@ -15,6 +16,9 @@ public:

static const char player_markers[3];

+ typedef std::pair <int, int> MyMove;
+ static const MyMove my_no_move (-1, -1);
+
ConnectFourState(int num_rows_ = 6, int num_cols_ = 7)
: player_to_move(1),
num_rows(num_rows_),


i.e., introduce a new type "MyMove" with std::pair and a constant. This code does not compile. If I remove those lines, it compiles with no problem.

.../monte-carlo-tree-search/games/connect_four.h:20:41: error: expected identifier before ‘-’ token
.../monte-carlo-tree-search/games/connect_four.h:20:41: error: expected ‘,’ or ‘...’ before ‘-’ token


However, on the same machine, I test the same part of code which compiles.

#include <utility>

int main ()
{
typedef std::pair <int, int> MyMove;
static const MyMove my_no_move (-1, -1);
return 0;
}

$ g++ temp.C -std=c++0x
$


Why? I admit the compiler on my machine is not updated which does not fully support c++11, but how come same lines of code have different result.

Answer

You cannot declare a member variable of a class like that.

Declare it as:

typedef std::pair <int, int> MyMove;
static const MyMove my_no_move;

And then define it outside the class as:

// The typedef MyMove is also scoped
const ConnectFourState::MyMove ConnectFourState::my_no_move(-1, -1);
Comments