作者chchwy (mat)
看板C_and_CPP
標題[問題] 請問關於 function object 的一段話
時間Sun Aug 21 20:52:00 2011
小弟我目前在念 C++ Standard Library: a Tutorial and Reference 這本書
書裡提到使用 function object 有三個優點 (比起原始的函數來說)
三個優點中有兩個我看懂了
1. function object 可以維護內部的狀態。
2. function object 速度比較快。
但是最後一點我看不懂為什麼 囧"
原文抄錄如下
Each function object has its own type.
Ordinary functions have different types only when their signatures differ.
However, function objects can have different types even when their signatures
are the same. In fact, each functional behavior defined by a function object
has its own type. This is a significant improvement for generic programming
using templates because you can pass functional behavior as a template
parameter. It enables containers of different types to use the same kind of
function object as a sorting criterion. This ensures that you don't assign,
combine, or compare collections that have different sorting criteria. You can
even design hierarchies of function objects so that you can, for example,
have different, special kinds of one general criterion.
上來請各位大大指點一下,謝謝。
--
UVa Problems I Solved
http://chchwy.blogspot.com/p/my-solved-acm-problems-list.html
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.115.158.103
→ james732:看起來就是讓type的限制可以更嚴格 08/21 20:58
推 tropical72:比對一下 stl/foreach1.cpp 與 stl/foreach2.cpp 作法 08/21 22:21
→ tropical72:或許會有些想法.. 08/21 22:23
→ loveme00835:因為是不同型態, 所以在編譯的時候就可以知道你傳入的 08/21 23:19
→ loveme00835:物件是屬於何種類別, 然後這時候假如call operator 08/21 23:20
→ loveme00835:實作在編譯時期已知, 編譯器就可以找到該區段程式碼 08/21 23:22
→ loveme00835:直接在stl algorithms的程式碼內做展開, 減少函式呼叫 08/21 23:22
→ loveme00835:次數, 但是如果是藉由函式指標來做, 這項資訊缺少了, 08/21 23:23
→ loveme00835:變成跟C語言程式一樣要到執行時期才能跳轉到某函式去 08/21 23:24
→ loveme00835:執行, 即使實作碼就在前面... 08/21 23:24