C++ 中的构造函数可以使用可变参数,可以使用 C++11 引入的可变参数模板实现。使用可变参数模板的构造函数可以接受任意数量和类型的参数。
下面是一个使用可变参数模板的构造函数的示例代码:
#include <iostream>
#include <string>
class Example {
public:
template<typename... Args>
Example(Args... args) {
std::cout << "Constructed with " << sizeof...(Args) << " arguments." << std::endl;
int main() {
Example example1;
Example example2(1, 2, 3);
Example example3("Hello", 4.2, 'a', std::string("World"));
return 0;
在上面的示例代码中,Example 类的构造函数使用了可变参数模板。这个构造函数接受任意数量和类型的参数,并在构造函数中输出了参数的数量。
在主函数中,我们创建了三个 Example 类的实例。example1 没有传递参数,example2 传递了三个整型参数,example3 传递了四个不同类型的参数。
输出结果如下:
Constructed with 0 arguments.
Constructed with 3 arguments.
Constructed with 4 arguments.
因此,可以看出使用可变参数模板的构造函数可以接受任意数量和类型的参数。