6
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
}
4

1 回答 1

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不完全是,但这不是极端情况之一。

于 2012-11-09T13:24:31.493 回答