比方說,我有以下元函數:通過緩存元功能
template <typename T>
struct make_pair {
using type = std::pair<
typename std::remove_reference<T>::type,
typename std::remove_reference<T>::type
>;
};
難道提高編譯速度要做到這一點(或者別的什麼)呢?
template <typename T>
struct make_pair {
using without_reference = typename std::remove_reference<T>::type;
using type = std::pair<without_reference, without_reference>;
};
我看到兩種可能性:
編譯器有每次看到
typename std::remove_reference<T>::type
時間做一些工作。使用中間別名有一些「緩存」行爲,它允許編譯器只做一次工作。編譯時性能是根據編譯器必須完成的模板實例化數量來衡量的。因爲
std::remove_reference<T>::type
指的是與std::remove_reference<T>::type
相同的類型,所以在這兩種情況下都只需要一個模板實例化,因此兩種實現都是等效的WRT編譯時性能。
我認爲B是對的,但我想確定。如果答案證明是特定於編譯器的,我大多會對Clang和GCC的答案感興趣。
編輯:
我一個基準測試程序的編制有一些數據的工作。測試程序做這樣的事情:
template <typename ...> struct result;
template <typename T>
struct with_cache {
using without_reference = typename std::remove_reference<T>::type;
using type = result<without_reference, ..., without_reference>;
};
template <typename T>
struct without_cache {
using type = result<
typename std::remove_reference<T>::type,
...,
typename std::remove_reference<T>::type
>;
{ };
using Result = with[out]_cache<int>::type;
這些都爲項目的10所彙編的平均時間,在result<>
10個000模板參數。
-------------------------
| g++ 4.8 | clang++ 3.2 |
-----------------------------------------
| with cache | 0.1628s | 0.3036s |
-----------------------------------------
| without cache | 0.1573s | 0.3785s |
-----------------------------------------
測試程序由可用腳本here生成。
我認爲沒有任何推測可以取代實際測量。請張貼一些時間數字,然後我們可以創建一個很好的理論來解釋它們。 –
我在clang上看到一段話,說他們爲模板實例而不是鏈表創建哈希表。我不知道他們是誰比較自己。 –
不做記憶的''''編譯器會變得非常慢。 – Yakk