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
}
最佳答案
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 不完全是,但这不是极端情况之一。
关于c++ - 字符串文字的模板参数推导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13308887/