【发布时间】:2020-04-13 00:48:35
【问题描述】:
假设我们有 2 个函数:
template <typename T> void callDecayExample1(T& t)
{
std::initializer_list<T> testList2{ 1, 2, 3 };
}
template <typename T> void callDecayExample2(T&& t)
{
std::initializer_list<std::decay_t<T>> testList{1, 2, 3};
}
我们这样称呼它们:
const int& i = 2;
int j = 10;
int& ref_j = j;
callDecayExample1(i); // deduced as const int&
callDecayExample1(ref_j);// deduced as int&
callDecayExample1(j); // deduced as int&
callDecayExample2(i); // deduced as const int&
callDecayExample2(ref_j);// deduced as int&
callDecayExample2(j); // deduced as int&
尽管两个函数的推导相似,但在第二个函数中,我必须使用 std::decay_t 来编译应用程序。为什么会这样?
我使用带有 /std:c++17 标志的 Visual Studio 2019
【问题讨论】:
-
在第一种情况下,
T是非引用类型,即int或const int对于这三种情况。在第二种情况下T,可以是引用类型,这会有所不同。您可以比较decltype(t)和T来形象化这一点。 -
@Jarod42 抱歉,已更正
标签: c++ templates c++17 metaprogramming visual-studio-2019