在下面的示例中,我希望行a.foo(j);将const限定符传递给模板化方法。
#include <iostream>
#include <type_traits>
struct A
{
template<typename T>
void foo(T i) const
{
std::cout << "Is const type: " << std::is_const<T>::value << "\n";
}
};
int main() {
A a;
int i = 0;
const int j = 0;
a.foo(i);
a.foo(j);
a.foo<decltype(i)>(i);
a.foo<decltype(j)>(j);
a.foo<int>(i);
a.foo<const int>(j);
return 0;
}然而,我从gcc和clang (c++17)获得的输出如下。
Is const type: 0
Is const type: 0
Is const type: 0
Is const type: 1
Is const type: 0
Is const type: 1第二行为false,而不是true。那么为什么自动模板演绎会删除cv限定符呢?有什么具体的原因吗?
PS。上面的例子可以找到这里
发布于 2019-12-18 18:16:20
对T类型的扣减将始终是衰减的。int const的衰变类型只是int。int[3]的腐朽类型是int*。
问题是,这个代码是正确的。
是的,在foo内部,您永远无法更改j的值。在foo内部,您有一个副本,它由foo来决定它是否希望自己的参数在函数体中是常数的。
但是,还有其他形式的扣减必须维护const才能用参数调用。这不是您的代码的解决方案,而只是一个示例:
template<typename T>
void frob(T& i)
{
std::cout << "Will it be const? " << std::is_const<T>::value << "\n";
}
auto main() -> int {
int const myInt = 9;
frob(myInt);
}要被调用,参数必须是int const&,所以这就是将要推导的内容。
https://stackoverflow.com/questions/59397717
复制相似问题