gpt4 book ai didi

c++ - 为什么执行顺序在 "Why Not Specialize Function Templates"中很重要

转载 作者:搜寻专家 更新时间:2023-10-31 01:52:50 26 4
gpt4 key购买 nike

我已经通过 VS2010 运行了以下代码。

#include <iostream>

template<class T> // (a) a base template
void f( T )
{ std::cout << "(a)" << std::endll;}

template<class T> // (b) a second base template, overloads (a)
void f( T* ) // (function templates can't be partially
{ std::cout << "(b)" << std::endll;}

template<> // (c) explicit specialization of (b)
void f<>(int*)
{ std::cout << "(c)" << std::endll;}

int main(int argc, char* argv[])
{
int *p = new int(10);
f( p ); // '(c)'

return 0;
}

////////////////

#include <iostream>

template<class T> // (a) same old base template as before
void f( T )
{ std::cout << "(a)" << std::endll;}

template<> // (c) explicit specialization, this time of (a)
void f<>(int*)
{ std::cout << "(c)" << std::endll;}

template<class T> // (b) a second base template, overloads (a)
void f( T* )
{ std::cout << "(b)" << std::endll;}

int main(int argc, char* argv[])
{
int *p = new int(10);
f( p ); // '(b)'

return 0;
}

输出结果为(c)。但是,如果我把(c)的代码块移到(b)的前面,那么输出结果就是(b)。我看过相关文章http://www.gotw.ca/publications/mill17.htm这里。仍然感到困惑。

为什么代码的顺序在这个案例中很重要?

最佳答案

我认为您已经掌握了问题中的大部分信息。问题是有两个基本模板是重载的,否则是不相关的。

如果仅在声明第一个模板时执行特化,则编译器将认为这是对 T == int* 的第一个模板的特化。现在,在声明两个模板后,当您执行调用时,编译器将只查看基本模板,并确定第二个模板更适合表达式。第二个模板没有专门化,因此使用基本模板定义。

我要强调的是:模板特化只有在选择了基本模板后才会发挥作用。它们不会影响编译器将选择哪个基本模板。

如果您在声明第二个模板之后移动特化,编译器将使用 T == int 将该特化与第二个基本模板匹配。在这种情况下,当编译器选择第二个模板作为 main 中调用的最佳匹配时,特化将启动,您将获得特化行为。

关于c++ - 为什么执行顺序在 "Why Not Specialize Function Templates"中很重要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11990019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com