-4

The following code doesn't compile:

#include <iostream> 
#include <set>
#include <utility>
using namespace std; 

template <typename T1, typename T2>  
class meta {
   pair<T1,T2> xy_pair; 

   public: 
   /* meta(const T1 & t1, const T2 & t2) : 
    xy_pair.first(t1), 
    xy_pair.second(t2)
    {}*/
  meta() : 
    xy_pair.first(T1()), 
    xy_pair.second(T2())
    {}
  void print() const{
      cout << xy_pair.first << endl; 
      cout << xy_pair.second << endl; 
  }  

}; 

int main(){
 meta<int,int> met_xy; 

}

I get the following compiler error:

[root@localhost STL]# g++ -std=c++0x sets.cpp -o sets
sets.cpp: In constructor ‘meta<T1, T2>::meta()’:
sets.cpp:16:16: error: expected ‘(’ before ‘.’ token
sets.cpp:16:16: error: expected ‘{’ before ‘.’ token
sets.cpp: In member function ‘void meta<T1, T2>::print() const’:
sets.cpp:20:29: error: expected primary-expression before ‘,’ token
sets.cpp:20:32: error: expected primary-expression before ‘>’ token
sets.cpp:20:33: error: expected primary-expression before ‘.’ token
sets.cpp:21:29: error: expected primary-expression before ‘,’ token
sets.cpp:21:32: error: expected primary-expression before ‘>’ token
sets.cpp:21:33: error: expected primary-expression before ‘.’ token
Rapptz
  • 20,807
  • 5
  • 72
  • 86

2 Answers2

3

You cannot initialize individual sub-members of the member object in the initializer list like this. Make it

meta() : xy_pair(T1(), T2()) {}

or simply

meta() {}

or in fact just omit the default constructor entirely - the compiler-generated one would do the same thing.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85
2

Your code should probably read as follows:

#include <utility>
#include <ostream>
#include <iostream>

template <typename T1, typename T2>  
class meta {
   std::pair<T1, T2> xy_pair;

public: 
    meta(const T1 & t1, const T2 & t2) : xy_pair(t1, t2) { }
    // note initialization of the whole member xy_pair, not its members
    meta() : xy_pair() { }

    void print() const {
       cout << xy_pair.first << endl; 
       cout << xy_pair.second << endl; 
    }
}; 

int main() {
   meta<int, int> meta_xy;
}
ildjarn
  • 62,044
  • 9
  • 127
  • 211
Phil Miller
  • 36,389
  • 13
  • 67
  • 90