DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

decltype c++11

decltype

It is the keyword in c++11, compiler use it to find out the type of a variable or expression.

Purpose / Benefits / Advantages :

  • It is used to evaluate the return type of template function.
  • It is used to evaluate the return type of auto also see priority example.

Source code with example:

//Header File
#include<iostream>
#include<typeinfo>

//FindMax function
template<typename T1, typename T2>
auto findMax(T1 x, T2 y) ->decltype(x > y ? x:y)
{
  return(x > y) ? x:y;
}

int main()
{
    std::cout<<"Decltype"<<std::endl;
    int x =5;
    decltype(x) X=7;
    std::cout<<"x:"<<x<<std::endl;
    std::cout<<"decltype:"<<X<<std::endl;
    std::cout<<"decltype Type:"<<typeid(X).name()<<std::endl;

    //Calling Find Max function
    auto res = findMax(3, 2.2);
    std::cout<<"Result:"<<res<<std::endl;
    std::cout<<"Type:"<<typeid(res).name()<<std::endl;

    auto res1 = findMax(1, 2.2);
    std::cout<<"Result1:"<<res1<<std::endl;
    std::cout<<"Type:"<<typeid(res1).name()<<std::endl;

    return 0;
}

Output:

Decltype
x:5
decltype:7
decltype Type:i
Result:3
Type:d
Result1:2.2
Type:d

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer