C++ decltype

Thought to write about decltype but after spending a little time with this keyword realized that the concept is really too simple to spend too much time on the topic. I am limiting this article to pointing the primary place where decltype should be used, and that is in declaring a return type from a template when it is unknown at compile time and must be deduced from the input parameters at run time. For example,


parameters t and u can be of types int and double and resulting type must be double. Or they could be string and string and resulting type has to be string. Syntax


in conjunction with the auto keyword ensures that the correct type will be returned to the caller of this function.

Example taken from MSDN:

// decltype
// The following code example declares the late-specified return type
// of template function Plus().
// The Plus function processes its two operands with the operator+ overload.
// Consequently, the interpretation of the plus operator (+) and the return
// type of the Plus function depends on the types of the function arguments.

#include <iostream>
#include <string>
#include <utility>
#include <iomanip>

using std::cout;
using std::endl;
using std::setprecision;
using std::forward;
using std::string;

template<typename T, typename U>
auto Plus(T&& t, U&& u) -> decltype(forward<T>(t) + forward<U>(u))
  return forward<T>(t) + forward<U>(u);

class X
  X(int data) : m_data(data) {}
  int dump() const { return m_data; }

  friend X operator+(const X& x1, const X& x2)  {   return X(x1.m_data + x2.m_data);  }

  int m_data;

int main()
  // Integer
  int i = 4;
  cout << "Plus(i, 9) = " << Plus(i, 9) << endl;

  // Floating point
  float dx = 3.7;
  float dy = 9.5;
  cout << setprecision(3) << "Plus(dx, dy) = " << Plus(dx, dy) << endl;

  // String
  string hello = "Hello, ";
  string world = "world!";
  cout << Plus(hello, world) << endl;

  // Custom type
  X x1(20);
  X x2(22);
  X x3 = Plus(x1, x2);
  cout << "x3.dump() = " << x3.dump() << endl;

  // Mixed types
  cout << "Plus(dy, i) = " << Plus(dy, i) << endl;

  return 0;




Cpp Programming

C++ 0x features

C++ Tidbits

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: