考虑以下示例:
#include <iostream>
template<typename T>
void f(T t) {
std::cout << t << '\n';
static_assert(std::is_same<T, int const*>::value, "T != int const*");
static_assert(std::is_same<decltype(t), int const*>::value, "decltype(t) != int const*");
}
template<typename T>
void g(T t) {
std::cout << t << '\n';
static_assert(std::is_same<T, int>::value, "T != int");
static_assert(std::is_same<decltype(t), int>::value, "decltype(t) != int");
t++;
}
int main()
{
int x = 22;
int const* px = &x;
f(px);
int const& rx = x;
g(rx);
}
代码正常执行。但是根据目前的规则我们得到:
-
T == int const*
和t
类型为int const*
在模板函数的实例化中f
在通话中f(px)
. -
T == int
和t
类型为int
在模板函数的实例化中g
在通话中g(rx)
.
我对第二个推导的第一个想法是与指针情况对称的东西,即 T == int const&
和 t
与类型 int const&
.
我想我知道编译器执行的当前推导过程是怎么回事。通过 §5.5,引用被删除在表达式 rx
中传递给 g
.即rx
的类型参数推导是 int const
.请注意,通过此更改,const
在 rx
的声明中不是顶级成为顶级const
.然后通过§14.8.2.1/2,第三个要点,const
在类型 int const
中被忽略因为它现在是顶级 const
.
对我来说,这个方案似乎相当人为。因此,我在想,为什么必须将 §5/5 应用于用于推导模板参数的表达式?必须有更强有力的理由来证明这条规则的合理性,我不知道。这就是我想知道的。谢谢。
最佳答案
关于理由,让我们首先考虑为什么 const
没有进入参数类型推导:
template< class Type >
void foo( Type v ) { v = 0; }
auto main() -> int
{
int const x = 3;
foo( x );
}
从机制上讲,这编译得很好,因为 C++11 §14.8.2.1/2 第三破折号是这样说的,“A
类型的顶级 cv 限定符在类型推导中被忽略”。
我想这样做的很大一部分原因是,否则各种实际参数 cv 限定会产生与函数完全相同的函数模板实例类型,因为顶级 cv 限定正式论点被忽略。到函数的类型。这样的实例化可以产生截然不同的效果。会很乱。
然后,关于为什么引用被删除,那么他们不是这个程序,
#if defined( USE_REF )
# define Q &&
auto kind = "ref";
#else
# define Q
auto kind = "non-ref";
#endif
template< class A1, class A2 >
void foo( A1 a1, A2 a2 )
{
a1 ^= a2;
a2 ^= a1;
a1 ^= a2;
}
#include <iostream>
#include <typeinfo>
auto main() -> int
{
using namespace std;
int Q a1 = 111;
int Q a2 = 222;
foo( a1, a2 );
cout << kind << ' ' << a1 << ' ' << a2 << endl;
}
将根据 USE_REF
以不同的顺序输出数字。
但事实并非如此。
那是因为引用的设计使得 a1
是对 int
的引用,在 C++03 中与 a1
没有区别> 这直接是一个 int
。
对于基本原理的更明确和更明智的观点(以上是非常合理的,但仍然只是我的想法),可能 Bjarne Stroustrup 的“C++ 的设计和进化”一书有一些东西.或不。很遗憾,我没有那本书。
关于c++ - 为什么在推导模板参数时应用 §5/5?规则不能不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24828832/