VC++ 2015 – Lazy generators

If you have ever used iterators in C# or Visual Basic, then this is essentially the same thing. You would need to enable the new experimental /await compiler option, same as in the previous blog entry.

std::experimental::generator<int> evens(size_t count)
{
  using namespace std::chrono;

  for (size_t i = 1; i <= count; i++)
  {
    yield i * 2;
    std::cout << "yielding..." << std::endl;
    std::this_thread::sleep_for(1s);
  }
}

Calling this method would be fairly straightforward.

void main_yield()
{
  for (auto ev : evens(7))
  {
    std::cout << ev << std::endl;
  }
}

And here’s the expected output.

yield_demo_cpp

I added the console output to demonstrate the laziness of the generator.

VC++ 2015 – Using resumable functions

Visual C++ 2015 has a new compiler option called /await that can be used to write and call resumable functions. Do note that this is an experimental feature and even the associated headers are in an experimental sub-directory. There is no UI option to turn this compiler option in VS 2015, so you would need to manually add it via the Additional Options box under the C/C++ property page.

To compile the samples in this blog entry, you would need the following includes.

#include <thread>
#include <future>
#include <iostream>
#include <experimental\resumable>
#include <experimental\generator>

Here’s a simple example async method that sums two numbers. To demonstrate the async-nature of the call, I’ve added a sleep of 2 seconds to slow down the operation.

std::future<int> sum_async(int x, int y)
{
  using namespace std::chrono;

  return std::async([x, y] 
  {
    std::this_thread::sleep_for(2s);
    return x + y; 
  });
}

The async function will execute the function asynchronously, typically in a separate thread, and return a future that will hold the result of the call when it’s completed. Now, here’s how this method can be called.

std::future<void> call_sum_async(int x, int y)
{
  std::cout << "** async func - before call" << std::endl;
  auto sum = await sum_async(x, y);
  std::cout << "** async func - after call" << std::endl;
}

The await keyword calls that method asynchronously and waits until the method executes to completion. And then control goes to the next line of code. At least in the version of VC++ 2015 I tested this on, if you use await, the return type needs to be a future.

Now, here’s a calling method that invokes this caller method.

void main_async()
{
  std::cout << "<< main func - before call" << std::endl;
  auto result = call_sum_async(7, 9);
  std::cout << "<< main func - after call" << std::endl;

  {
    using namespace std::chrono;
    std::cout << "<< main func - before sleep" << std::endl;
    std::this_thread::sleep_for(3s);
    std::cout << "<< main func - after sleep" << std::endl;
  }

  result.get();
  std::cout << "<< main func - after get" << std::endl;
}

To show that the async method actually does execute asynchronously, I added a sleep block in the calling method. Here’s what the output looks like.

async_demo_cpp

Notice how the calling method continues to execute. And then once the async method has completed it returns control back to the main thread. The await keyword just makes it so easy to do this. You write your code just as you would write synchronous code, and all the async-ness is hidden from you. Well not really hidden, but handled for you smoothly.

Oh by the way, I am back to blogging after a bit of a hiatus. Expect to see me post far more frequently going forward.

VS14 CTP – Implement Pure Virtuals

This refactoring option implements stub-functions for all pure virtuals in one or all base classes. Here’s an example.

class Person
{
public:

  virtual std::string GetName() = 0;
  virtual void SetName(std::string) = 0;
};

class DbEntity
{
public:
  virtual int GetId() = 0;
  virtual void SetId(int) = 0;
};

class Employee : Person, DbEntity
{
public:
  Employee();
};

If you right click on a specific base class, you’ll get an option to just implement pure virtuals for that class. If you right click on the derived class name, you’ll get the option to implement all pure virtuals for all base types.

imppurevirts

This is what you’ll end up with (in the header).

class Employee : Person, DbEntity
{
public:
  Employee();
  // Inherited via Person

  virtual std::string GetName() override;

  virtual void SetName(std::string) override;

  // Inherited via DbEntity

  virtual int GetId() override;

  virtual void SetId(int) override;

};

Corresponding definitions (empty ones) will be generated in the cpp file.

VS14 CTP – Move Definition Location

The CTP adds a refactoring option to move a function definition from header to cpp, or vice-versa. Just right-click on the definition, choose Refactor/Move Definition Location and that’s it.

// h file
class Employee
{
public:
  Employee();

  int Foo(int x, int y);
};

// cpp file
Employee::Employee()
{
}

int Employee::Foo(int x, int y)
{
  return 0;
}

mdl01

Now your code looks like this.

class Employee
{
public:
  Employee();

  int Foo(int x, int y)
  {
    return 0;
  }
};

You can do the reverse too. There seems to be a bug in this CTP though – when you move from the h to the cpp, it does not prefix the class-name, so you get this.

int Foo(int x, int y)
{
  return 0;
}

I would assume that this would be fixed in the RTM.

Seemingly a minor feature, but it is convenient and once you get used to it, you’ll start to miss it when you don’t have it (when using an older version or a different IDE).

VS14 CTP – Create Declaration / Definition

The CTP 2 has a mostly stable implementation of the “Create Declaration / Definition” refactoring tool for your C++ projects. It lets you auto generate the definition or declaration of a member function. Example, if you have a class called Employee, declared in Employee.h and defined in Employee.cpp, you can type in a function declaration into the .h file and have the body auto-generated for you in the cpp file.

cdd02

You’ll get an empty definition.

int Employee::Foo(int x, int y, double d)
{
    return 0;
}

You can do the reverse too. Say you want to add an overload without the double paramater. Just copy paste this definition, remove the double paramater and then use the refactoring option.

cdd01

That’ll generate this for you.

int Foo(int x, int y);

Quite useful. That said, I wish it would do something like this. If I have code as follows.

Employee e;
e.Bar();

If you right click Bar() and choose this refactoring option, you’ll get a message that says – “The selected text does not contain any function signatures.”

Now that would have been handy. C# has had that for at least 2 iterations now.

VS14 CTP – User-defined literals

User-defined literals is a C++ 11 feature that’s been implemented in the VS 14 CTP. Some of the standard headers have already been updated to define user defined literals. Example, <string> has an s-suffix for string literals. So you can do the following now, and both lines of code are identical.

auto s1 = "hello"s;
auto s2 = string("hello");

The definition in <string> (as of the CTP) looks like this:

inline string operator "" s(const char *_Str, size_t _Len)
  { // construct literal from [_Str, _Str + _Len)
  return (string(_Str, _Len));
  }

Here’s a common example used to demonstrate how you’d use user defined literals in your code. Consider the following Weight class.

struct Weight
{
  WeightUnitType Unit;

  double Value;

  double Lb;

  Weight(WeightUnitType unitType, double value)
  {
    Value = value;
    Unit = unitType;

    if (Unit == WeightUnitType::Lb)
    {
      Lb = value;
    }
    else
    {
      Lb = 2.2 * value;
    }
  }
};

Now here’s how you’d define _kg and _lb literal operators for this class.

Weight operator "" _kg(long double value)
{ 
  return (Weight(WeightUnitType::Kg, static_cast<double>(value)));
}

Weight operator "" _lb(long double value)
{
  return (Weight(WeightUnitType::Lb, static_cast<double>(value)));
}

And here’s how you’d use them in your code.

auto w1 = 10.0_kg;
auto w2 = 22.0_lb;

cout << (w1.Lb == w2.Lb) << endl; // outputs 1 (true)

Be aware that your literals will need to have a _ as the start of the suffix. Else, you’ll just get an error:

literal suffix identifiers that do not start 
with an underscore are reserved

I would assume that <string> does not need an underscore as it’s permitted as a special case.

VS14 CTP – auto return type

Instead of implementing all the C++ 11 features first and then targeting C++ 14, the VC++ team have taken an approach where they will implement both in parallel. This will allow them to implement popular C++ 14 features ahead of less popular C++ 11 features. Either way, at some point, they will have a release which completely supports C++ 11 and C++ 14. One very commonly requested C++ 14 feature is auto/decltype(auto) return types and the CTP supports both.

Here’s an example, where using it saves some typing and the code looks cleaner.

auto Foo()
{
  map<int, vector<pair<int, string>>> vec;
  return vec;
}

Of course, that is subjective, and some people may feel that the auto is confusing there. It is more useful with templates where the return type would normally need a decltype.

template<class T1, class T2> auto Foo(T1 a, T2 b)
{
  return a + b;
}

You can use it with class methods, and even do forward declarations.

class C
{
public: 
  auto Foo();
};

auto C::Foo()
{
  return 10;
}

Multiple returns are also supported, and that’s also for your lambdas.

auto Bar()
{
  C c;
  if (c.Foo() < 10)
  {
    return 3.3;
  }

  return 1.7;
}

Using decltype(auto) gives you even more flexibility. Consider this code.

int F1()
{
  return 5;
}

int  i = 5;
int& F2()
{
  return i;
}

Now if you call these as follows.

  auto f1 = F1(); // int - correct
  auto f2 = F2(); // int - inaccurate, lost original type
  decltype(auto) f3 = F1(); // int - correct
  decltype(auto) f4 = F2(); // int& - correct

It’s the same with templates, where you can save on a decltype.

struct T
{
  int& Foo(int& i)
  {
    return i;
  }

  double Foo(double& d)
  {
    return d;
  }

  template<class T> decltype(auto) NewWay(T& t)
  {
    return Foo(t);
  }

  template<class T> auto OldWay(T& t) -> decltype(Foo(t))
  {
    return Foo(t);
  }
};

That’s a simple example, but library writers would appreciate this as it significantly simplifies their code and makes it way easier to understand when going through someone else’s code.