【问题标题】:How does template in c ++ actually work in background?c ++中的模板实际上如何在后台工作?
【发布时间】:2020-06-20 15:59:29
【问题描述】:

** 为什么代码的输出是

  x = 1 count = 0

  x = 1 count = 1

 x = 1.1 count = 0

**

//code for template
#include <iostream>
using namespace std;

template <typename T>
void fun(const T&x)
{
    static int count = 0;
    cout << "x = " << x << " count = " << count << endl;
    ++count;
    return;
}

int main()
{
    fun<int> (1);//for int
    cout << endl;
    fun<int>(1);//for int
    cout << endl; 
    fun<double>(1.1);//for int
    cout << endl;
    return 0;
}

Compiler 是否在上述代码中为 c++ 中的每种数据类型创建一个模板函数的新实例,以及我们如何在调用函数 fun() 时将右值分配给引用变量?

【问题讨论】:

  • 恕我直言,理解模板的最简单方法是将它们视为模板,就像艺术家模板一样。在评估之前替换数据类型。模板没有“背景”。将它们视为模板可以解释为什么模板不能在 cpp 文件中。

标签: c++ templates c++14


【解决方案1】:

在您的代码中,您使用模板创建了两个函数,一个函数使用int 类型,另一个函数使用double 类型:

void fun(const int &x)
{
    static int count = 0;
    cout << "x = " << x << " count = " << count << endl;
    ++count;
    return;
}

void fun(const double &x)
{
    static int count = 0;
    cout << "x = " << x << " count = " << count << endl;
    ++count;
    return;
}

编译器可以将第二个fun&lt;int&gt;(1)识别为对上述整数函数的调用,因此不需要生成第三个函数。

通过引用传递或const 引用与template 函数一样,与普通函数一样; template 只影响数据类型,不影响参数的传递方式。

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2015-01-30
    • 1970-01-01
    • 2021-01-21
    • 2011-09-27
    • 2021-12-16
    相关资源
    最近更新 更多