字符串文字的模板参数推导

时间:2012-11-09 13:20:11

标签: c++ arrays templates pointers c++11

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
}

1 个答案:

答案 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 不完全,但这不是一个极端的案例。