/*Class template argument deduction in C++ is a feature introduced in C++17 that
allows the compiler to deduce the template arguments for class templates based on
the constructor arguments. This can simplify the syntax of creating objects of
class templates, making it more readable and less prone to errors. Here is a
simple example to illustrate class template argument deduction:
We make a member variable private so that it cannot be accessed directly from
outside the class. This is called data encapsulation and helps to protect the
internal state of an object from being accidentally or intentionally modified by
code outside the class. It also provides a level of abstraction and prevents the
user of the class from having to worry about the internal implementation details
of the class. By controlling access to the member variables through public member
functions, the class can ensure that the data is manipulated in a safe and
controlled manner.
*/
#include <iostream>
#include <string>
template <typename T>
class Person {
public:
// Constructor definition, variable variablename_ is the name of a variable called as member
//here &T is used to get the referece of the value
explicit Person(const T& value) : variablename_(value) {}
T getName() const { return variablename_; }
//here we are declaring a member variable
private:
T variablename_;
};
int main() {
// No need to specify the template argument, the compiler will deduce it based on the argument
Person<std::string> p("Adarsh");
std::cout << p.getName() << std::endl; // Output: Adarsh
Person<int> q(12345);
std::cout << q.getName() << std::endl; // Output: 12345
return 0;
}
To embed this project on your website, copy the following code and paste it into your website's HTML: