[問題] 關於 template instantiation 的問題

看板C_and_CPP作者 ( )時間15年前 (2010/11/24 00:35), 編輯推噓7(7014)
留言21則, 7人參與, 最新討論串1/1
下面這兩行是正確的: vector<int> v; remove_if(v.begin(), v.end(), bind1st(less<int>(), 0)); 如果把 less<int> 換成 less<const int> 或是 less<const int&> 都會 compile error 但如果是像下面這麼寫: vector<int>::iterator iter = v.begin(); less<const int&>()(*iter, 0); less<> 中的東西不論是 <int>, <const int>, <const int&> 都可以正常 compile, 請問這是什麼原因呢? 錯誤訊息如下: In file included from /usr/include/c++/4.4/bits/stl_function.h:712, from /usr/include/c++/4.4/functional:50, from vec.cc:2: /usr/include/c++/4.4/backward/binders.h: In instantiation of ‘ std::binder1st<std::less<const int&> >’: vec.cc:11: instantiated from here /usr/include/c++/4.4/backward/binders.h:117: error: ‘typename _Operation::result_type std::binder1st<_Operation>::operator()(typename _Operation::second_argument_type&) const [with _Operation = std::less<const int&>]’ cannot be overloaded /usr/include/c++/4.4/backward/binders.h:111: error: with ‘typename _Operation::result_type std::binder1st<_Operation>::operator()(const typename _Operation::second_argument_type&) const [with _Operation = std::less<const int&>]’ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 139.175.68.252

11/24 01:13, , 1F
個人猜測是less繼承binary function的定義,但second_a
11/24 01:13, 1F

11/24 01:14, , 2F
rgument_type又只是純粹的typedef,沒有用traits取出
11/24 01:14, 2F

11/24 01:14, , 3F
可能會有const重複的問題?!
11/24 01:14, 3F

11/24 01:20, , 4F
看起來像是 binder1st 的 const 重複問題...
11/24 01:20, 4F

11/24 01:25, , 5F
上次好像在comp.lang.c++看到類似的問題
11/24 01:25, 5F

11/24 01:27, , 6F
原理就跟這個類別一樣 http://codepad.org/YAkfTa56
11/24 01:27, 6F

11/24 01:28, , 7F
因為都有 const, 變成兩個函式是一樣的
11/24 01:28, 7F

11/24 01:33, , 8F
唉 讓我想到reference to reference的陷阱
11/24 01:33, 8F

11/24 01:34, , 9F
11/24 01:34, 9F

11/24 01:34, , 10F
看完之後我覺得這真是個時代錯誤..
11/24 01:34, 10F

11/24 01:35, , 11F
因為有109的問題所以多加了一個operator()結果變成新的問
11/24 01:35, 11F

11/24 01:35, , 12F
題..
11/24 01:35, 12F

11/24 01:49, , 13F
http://tinyurl.com/2asp7qy 這裡也有一串類似的問題
11/24 01:49, 13F

11/24 01:49, , 14F
結論是 放棄那個時代錯誤的std::bind1st吧
11/24 01:49, 14F

11/24 01:50, , 15F
現在是std::(tr1::)bind的時代了XD
11/24 01:50, 15F

11/24 01:54, , 16F
XDD
11/24 01:54, 16F

11/24 07:35, , 17F
less<> 是 class template 那樣寫沒問題. bind1st 是
11/24 07:35, 17F

11/24 07:36, , 18F
function template 而 top-level cv-qualifier 對 overload
11/24 07:36, 18F

11/24 07:41, , 19F
是沒區別的. 好像是這樣沒時間仔細驗證
11/24 07:41, 19F

11/24 08:43, , 20F
抱歉說錯了~
11/24 08:43, 20F

11/25 10:49, , 21F
感謝各位指教 m(_ _)m
11/25 10:49, 21F
文章代碼(AID): #1Cw-rRWM (C_and_CPP)