Friday, February 15, 2013

C++ decltype

  • The decltype operator is a C++11 feature. 
  • Note:- Use "g++ -std=c++0x filename.cpp" to enable this feature.
  • The decltype operator allows to querying the type of an expression.
  • In decltype(e) if e is an identifier, expression or class member decltype(e) is defined as type of e.
  • In decltype(e) if e is a function call decltype(e) is defined as return type of the function.
  • The operand of decltype is not evaluated.

Demonstrate the basic usage of decltype operator.

#include <iostream>
using namespace std;

int func1() { return 100; }

struct MyStruct {
   double x;

class MyClass {
       int x;
       MyClass() { x = 200; };
       int getx() { return x; }

int main() {

   int x = 100;
   decltype(x) y = x; // type of y is int

   decltype(func1()) z = x; // type of z is int

   MyStruct* s = new MyStruct();
   decltype(s->x) x1 = 100; // type of x1 is double

   MyClass* c = new MyClass();
   decltype(c->getx()) x2 = x; // type of x2 is int

   int a[10];
   decltype(a) a1; // type of a1 is int[10]

   return 0;


Post a Comment

Contact Form


Email *

Message *

Back to Top