0

C++11 では、テンプレート関数のテンプレート引数にデフォルトを設定できることを理解しました。これまでは、クラスのみに許可されていました。

C++11 のテンプレート引数にデフォルトを入れると、以下のような意味になるといつも思っていました。

 // C++11 target code
 template<class Iterator, class AFunctor=mybinary_fnctr>
 void myFunction(Iterator first, Iterator last, AFunctor fnctr);

代わりに、従来のC++が機能すると信じて、次のことを試みました

 // C++ traditional
 template<class Iterator, class AFunctor>
 void myFunction(Iterator first, Iterator last, AFunctor fnctr=mybinary_fnctr);

以下のサンプルコードで発生したエラーは次のとおりです

 error: no matching function for call to ‘algo(__gnu_cxx::__normal_iterator<A*,
 std::vector<A, std::allocator<A> > >, __gnu_cxx::__normal_iterator<A*, 
 std::vector<A, std::allocator<A> > >)’

コンパイラはテンプレート引数の 1 つにデフォルトを設定しようとしていますか (構文は少し異なります)、それとも何か間違っていますか?

 namespace util {
 template<class T>
  int get(const T& obj);
 }

 class A {
  public:
   A(int a): data_(a) {}
   int data() const { return data_; }
  private:
   int data_;
  };

  namespace util {
  template<>
  int get<A>(const A& obj) {
   return obj.data();
  } }

 template <class Iterator,class GetFunction>
 void algo(Iterator first, Iterator last, 
 GetFunction foo=boost::bind(&util::get<typename Iterator::value_type>,_1)) 
 {
  while(first != last) {
   cout << foo(*first) << endl;
   ++first;
  } }

 int main() {
  A cntr[] = { A(10), A(20), A(30) };
  A* p = cntr;
  vector<A> ptr(p, p+3);

  algo(ptr.begin(), ptr.end()); // doesn't build
  //algo(cntr, cntr+3, boost::bind(&util::get<A>,_1)); // ok
  }
4

0 に答える 0