【问题标题】:Template function call parameter constructor模板函数调用参数构造函数
【发布时间】:2021-02-01 15:59:44
【问题描述】:

我有一个模板函数,然后我将一个简单的类传递给它。问题是为什么要调用构造函数。我研究参数推导,但似乎它们不同。

所以我对这个案例有一些相关的问题:

  1. 这背后的概念是什么?
  2. 我可以在使用这个时提供任何真实世界的示例吗?
  3. 在示例中,仅调用了单个参数 Ctr。如何调用多个参数Ctr?
#include <iostream>
#include <string>
using namespace std;
class Bar
{
public:
    Bar(int v)
    {
        cout << "BAR_1 ctr called" << endl;
        cout << v << endl;
    }
    
    Bar(int v1, int v2)
    {
        cout << "BAR_2 ctr called" << endl;
        cout << v1 << " " << v2 << endl;
    }
};
template<class CT>
void do_foo(const CT& t)
{
    cout << "foo_1 called" << endl;
    return;
}
template<class CT>
void do_foo(const CT& t, const CT& t2)
{
    cout << "foo_2 called" << endl;
    return;
}
int main()
{
    do_foo<Bar>(10);
    do_foo<Bar>(11,12);
    return 0;
}

这是输出

BAR_1 ctr called                                                                                                                     
10                                                                                                                                   
foo_1 called                                                                                                                         
BAR_1 ctr called                                                                                                                     
12                                                                                                                                   
BAR_1 ctr called                                                                                                                     
11                                                                                                                                   
foo_2 called

【问题讨论】:

  • 请每个问题回答一个问题。我允许自己在回答中回答一些问题,而忽略了其余部分;)

标签: c++ templates


【解决方案1】:

为什么调用构造函数实际上与涉及模板的事实无关。你会得到类似的输出:

void foo(const Bar& t)
{
    cout << "foo called" << endl;
}

int main() {
    foo(42);
}

当您使用42 作为参数调用foo 时,编译器会考虑一个用户定义的转换:foo(const Bar&amp;) 采用Bar,您传递一个int,存在从int 到@ 的转换987654328@ 通过Bar 的构造函数。一切都好。 42 用于创建一个Bar 并传递给foo


这里模板的作用是,如果调用

 do_foo(42);

然后模板参数推导将T 推导出为int 并且您正在调用do_foo&lt;int&gt;(42);(即不会构造Bar)。但是,当您显式指定模板参数时,则不会执行任何推演,do_foo&lt;Bar&gt; 只能带一个Bar 参数。

【讨论】:

    【解决方案2】:

    在示例中,仅调用了单个参数 Ctr。如何调用多个参数Ctr?

    当你打电话时

    do_foo<Bar>(11,12);
    

    你用两个参数调用do_foo&lt;Bar&gt;(),所以只有两个参数版本

    template<class CT>
    void do_foo(const CT& t, const CT& t2)
    

    匹配。

    如果要匹配双参数构造函数,肯定可以显式构造一个Bar对象(观察do_foo()CT模板参数可以推导出来)

     do_foo(Bar{11,12});
    

    或者您可以使用方括号将两个整数传递给单个对象(但您必须再次显式 do_foo() 的模板参数

     do_foo<Bar>({11,12}); 
    

    【讨论】:

      猜你喜欢
      • 2017-06-26
      • 1970-01-01
      • 2019-03-14
      • 2016-01-02
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 2021-07-13
      • 2016-09-02
      相关资源
      最近更新 更多