template<typename T>
void print_size(const T& x)
{
std::cout << sizeof(x) << '\n';
}
int main()
{
print_size("If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.");
// prints 115
}
这在最近的g ++编译器上打印115。显然,T
被推断为数组(而不是指针)。标准是否保证了这种行为?我有点惊讶,因为以下代码打印了指针的大小,我认为auto
的行为与模板参数推导完全相同?
int main()
{
auto x = "If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.";
print_size(x);
// prints 4
}
答案 0 :(得分:8)
auto
完全符合 1 之类的模板参数推导。完全像T
!
比较一下:
template<typename T>
void print_size(T x)
{
std::cout << sizeof(x) << '\n';
}
int main()
{
print_size("If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.");
// prints 4
auto x = "If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.";
print_size(x);
// prints 4
}
有了这个:
template<typename T>
void print_size(const T& x)
{
std::cout << sizeof(x) << '\n';
}
int main()
{
print_size("If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.");
// prints 115
const auto& x = "If you timidly approach C++ as just a better C or as an object-oriented language, you are going to miss the point.";
print_size(x);
// prints 115
}
1 不完全,但这不是一个极端的案例。