C++17 initializer_list

在C++17中, 对于模版类对象的生成不需要声明模版参数,可以直接进行初始化,模版参数交由编译器去推断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>
#include <type_traits>
using namespace std;
template <typename T1, typename T2>
class MyClass
{
private:
T1 t1;
T2 t2;

public:
MyClass(T1 t1 = T1(), T2 t2 = T2()) {}

void printSizeOfDataTypes()
{
cout << "\nSize of t1 is " << sizeof(t1) << " bytes." << endl;
cout << "\nSize of t2 is " << sizeof(t2) << " bytes." << endl;
}
};

int main ( ) {
//Until C++14
MyClass<int, double> obj1;
obj1.printSizeOfDataTypes( );
//New syntax in C++17
MyClass obj2( 1, 10.56 );
return 0;
}