- 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.
推薦閱讀
- Mastering C# Concurrency
- 21天學(xué)通C++(第6版)
- SharePoint Development with the SharePoint Framework
- Java 9模塊化開(kāi)發(fā):核心原則與實(shí)踐
- SQL Server 2016數(shù)據(jù)庫(kù)應(yīng)用與開(kāi)發(fā)
- Java EE 7 Performance Tuning and Optimization
- C語(yǔ)言程序設(shè)計(jì)
- ElasticSearch Cookbook(Second Edition)
- 零基礎(chǔ)學(xué)Kotlin之Android項(xiàng)目開(kāi)發(fā)實(shí)戰(zhàn)
- C#程序設(shè)計(jì)(項(xiàng)目教學(xué)版)
- Emgu CV Essentials
- Node.js 12實(shí)戰(zhàn)
- 智能手機(jī)故障檢測(cè)與維修從入門(mén)到精通
- Lift Application Development Cookbook
- 零基礎(chǔ)學(xué)C++(升級(jí)版)