假设我有以下元函数:
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
相同的类型,所以在两种情况下都只需要一个模板实例化,因此这两种实现在编译时性能方面是等效的。
我认为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;
这些是在 result<>
中使用10,000个模板参数进行10次编译的平均时间。
-------------------------
| g++ 4.8 | clang++ 3.2 |
-----------------------------------------
| with cache | 0.1628s | 0.3036s |
-----------------------------------------
| without cache | 0.1573s | 0.3785s |
-----------------------------------------
测试程序是由一个可在这里获取的脚本生成的。
模板
编译器将会非常慢。 - Yakk - Adam Nevraumont