【发布时间】:2021-02-01 15:59:44
【问题描述】:
我有一个模板函数,然后我将一个简单的类传递给它。问题是为什么要调用构造函数。我研究参数推导,但似乎它们不同。
所以我对这个案例有一些相关的问题:
- 这背后的概念是什么?
- 我可以在使用这个时提供任何真实世界的示例吗?
- 在示例中,仅调用了单个参数 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
【问题讨论】:
-
请每个问题回答一个问题。我允许自己在回答中回答一些问题,而忽略了其余部分;)