- Mastering C++ Programming
- Jeganathan Swaminathan
- 184字
- 2021-07-02 18:28:47
Template type auto-deduction for class templates
I'm sure you will love what you are about to see in the sample code. Though templates are quite useful, a lot of people don't like it due to its tough and weird syntax. But you don't have to worry anymore; take a look at the following code snippet:
#include <iostream>
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;
}
The preceding code can be compiled and the output can be viewed with the following commands:
g++-7 main.cpp -std=c++17
./a.out
The output of the program is as follows:
Size of t1 is 4 bytes.
Size of t2 is 8 bytes.
推薦閱讀
- Vue.js設(shè)計(jì)與實(shí)現(xiàn)
- Python程序設(shè)計(jì)教程(第2版)
- Java EE 6 企業(yè)級(jí)應(yīng)用開發(fā)教程
- Access 2010數(shù)據(jù)庫(kù)基礎(chǔ)與應(yīng)用項(xiàng)目式教程(第3版)
- Hands-On Swift 5 Microservices Development
- Highcharts Cookbook
- Visualforce Developer’s guide
- ASP.NET程序開發(fā)范例寶典
- Mastering Docker
- C++程序設(shè)計(jì)教程
- Scala Functional Programming Patterns
- Python Programming for Arduino
- JavaScript Concurrency
- H5匠人手冊(cè):霸屏H5實(shí)戰(zhàn)解密
- 微信公眾平臺(tái)開發(fā)最佳實(shí)踐