Default template arguments for function templates

This is yet another C++ 11 feature that’s now supported in VC++ 2013. Until now, the following code would not compile with VC++.

template <typename T = int> void Foo(T t = 0) { }

// error C4519: default template arguments are only 
// allowed on a class template

Visual C++ 2013 compiles this fine, and the template type is inferred correctly.

Foo(12L); // Foo<long>
Foo(12.1); // Foo<double>
Foo('A'); // Foo<char>
Foo(); // Foo<int>

The usefulness of this feature is more evident in the following example.

template <typename T> class Manager 
{
public:
  void Process(T t) { }
};

template <typename T> class AltManager
{
public:
  void Process(T t) { }
};

template <typename T, typename M = Manager<T>> void Manage(T t)
{
  M m;
  m.Process(t);
}

Manage(25); // Manage<int, Manager<int>>
Manage<int, AltManager<int>>(25); // Manage<int, AltManager<int>>

Not all arguments need to have defaults.

template <typename B, typename T = int> void Bar(B b = 0, T t = 0) { }

Bar(10); // Bar<int, int>
Bar(10L); // Bar<long, int>
Bar(10L, 20L); // Bar<long, long>
Bar(); // will not compile

When you have overloaded function templates with default arguments, you can run into compiler errors when the type cannot be inferred.

template <typename T = int> void Foo(T t = 0) { }
template <typename B, typename T = int> void Foo(B b = 0, T t = 0) { }

Foo(12L); // will not compile
Foo(12.1); // will not compile
Foo('A'); // will not compile
Foo(); // Foo<int>

So, that’s one thing to watch out for when using default template arguments with function templates.

VC++ 2013 support for delegating constructors

This is something C# has had for ages, so it is great to finally get it in C++ too. The compiler feature allows a type’s constructor (the delegating constructor) to have another constructor of the type in its initialization list. So when you previously had to write code like this.

class Error
{
public:
  Error()
  {
    Init(0, "Success");
  }

  Error(const char* message)
  {
    Init(-1, message);
  }

  Error(int errorCode, const char* message)
  {
    Init(errorCode, message);
  }

private:
  void Init(int errorCode, const char* message)
  {
    //...
  }
};

With delegating constructors, you can now write it as following.

class Error
{
public:
  Error() : Error(0, "Success")
  {
  }

  Error(const char* message) : Error(-1, message)
  {
  }

  Error(int errorCode, const char* message)
  {
    // ...
  }
};

Bonus reading – Here’s a humorous article written 10 years ago (May 2003) by Herb Sutter and Jim Hyslop on delegating constructors, way before the standards body started considering it as a serious proposal.

Tuple implementation via variadic templates

I took a look at the std tuple header file (which I believe is authored/maintained by Stephan T. Lavavej of the VC++ team – original code by P.J. Plauger) and it would be an understatement to say that my head was spinning for a while just going through the code. To understand better how it was implemented, I simplified it down and extracted out the minimal code required to instantiate a tuple and to access its values (and be able to both read and write). It helped me understand how variadic templates are typically used with recursive expansion to significantly reduce lines of code when designing template classes.

// tuple 
template<class... _Types> class tuple;

// empty tuple
template<> class tuple<> {};

// recursive tuple definition
template<class _This,
  class... _Rest>
  class tuple<_This, _Rest...>
  : private tuple<_Rest...>
{ 
public:
  _This _Myfirst;
};

The recursive specialization uses inheritance so that we’ll end up with members for every argument type specified for the tuple. To access a tuple value, a tuple_element class is used as a sort of accessor class.

// tuple_element
template<size_t _Index, class _Tuple> struct tuple_element;

// select first element
template<class _This, class... _Rest>
struct tuple_element<0, tuple<_This, _Rest...>>
{
  typedef _This& type;
  typedef tuple<_This, _Rest...> _Ttype;
};

// recursive tuple_element definition
template <size_t _Index, class _This, class... _Rest>
struct tuple_element<_Index, tuple<_This, _Rest...>>
  : public tuple_element<_Index - 1, tuple<_Rest...> >
{ 
};

Again, recursive inheritance is used, and the 0th case is specialized as well. Notice the two typedefs, one of them is a reference to the type of the value, and the other represents the tuple with the same arguments as the tuple_element. So, given an _Index value, we can retrieve the type of the tuple and the type of the tuple value for that recursion level. This is used in the get method.

// get reference to _Index element of tuple
template<size_t _Index, class... _Types> inline
  typename tuple_element<_Index, tuple<_Types...>>::type
  get(tuple<_Types...>& _Tuple)
{
  typedef typename tuple_element<_Index, tuple<_Types...>>::_Ttype _Ttype;
  return (((_Ttype&) _Tuple)._Myfirst);
}

Notice the return type, it uses the type typedef defined above. Similarly, the tuple is cast to the _TType typedef defined above and then we access the _Myfirst member (which represents the value). Now you can write code as follows.

tuple<int, char> t1;
get<0>(t1) = 959;
get<1>(t1) = 'A';

auto v1 = get<0>(t1);
auto v2 = get<1>(t1);

Now, this goes without saying, but I’ll say it just to be sure – but this is just for demonstration. Do not use this in production code, instead use std::tuple which does all this and lots more (there’s a reason it’s 800 lines long).

Variadic templates and recursive specialization

A typical approach used with variadic templates is to specialize it for one argument with the rest of the arguments being optional (which works recursively). Here’s a rather naïve example which is probably an example of how not to use variadic templates, but it helped me understand variadic templates better.

template<typename... Args> class Test;

// Specialization for 0 arguments
template<> class Test<>
{
};

// Specialization for at least 1 argument

template<typename T1, typename... TRest> class Test<T1, TRest...> 
  : public Test<TRest...>
{
public:
  T1 Data;

  // This will return the base type
  Test<TRest...>& Rest() 
  {
    return *this;
  }
};

void Foo()
{
  Test<int> data;
  data.Data = 24;

  Test<int, int> twovalues;
  twovalues.Data = 10;
  // Rest() returns Test<int>
  twovalues.Rest().Data = 11;

  Test<int, int, char*> threevalues;
  threevalues.Data = 1;
  // Rest() returns Test<int, int>
  threevalues.Rest().Data = 2;
  // Rest().Rest() returns Test<char*>
  threevalues.Rest().Rest().Data = "test data";
}

Please be aware that no one ever writes code like this. There are correct ways to do this that I will write about in this blog. This example was merely for academic purposes.

Update – I’ve written a follow-up blog entry that shows the proper way to use variadic templates.

Variadic templates – The sizeof… operator

The implementation of variadic templates includes a sizeof… operator that returns the number of template arguments in the parameter pack.

template<typename... Args> class Test
{
public:
  size_t GetTCount()
  {
    return sizeof...(Args);
  }
};

// . . .

Test<int> data;
size_t args = data.GetTCount(); //1

Test<int, int, char*> data2;
args = data2.GetTCount(); //3

Test<int, float> data3;
args = data3.GetTCount(); //2

It’s really more of a count-of here but I guess they chose to reuse an existing operator that’s familiar to C++ developers.

Variadic templates in VC++ 2013

The VC++ 2013 compiler supports variadic templates. They are templates that can take a variable number of template arguments. In my opinion, it’s more a feature for library authors than for library consumers, so I am not sure how popular its use will be among end-user C++ developers. Here’s a very simple example that shows variadic templates in action.

// Variadic template declaration
template<typename... Args> class Test;

// Specialization 1
template<typename T> class Test<T>
{
public:
  T Data;
};

// Specialization 2
template<typename T1, typename T2> class Test<T1, T2>
{
public:
  T1 Left;
  T2 Right;
};

void Foo()
{
  Test<int> data;
  data.Data = 24;

  Test<int, int> twovalues;
  twovalues.Left = 12;
  twovalues.Right = 15;
}

The intellisense kicks in and works beautifully too when using variadic templates. I will be trying to blog more on the use of variadic templates in the near future.

Casablanca – showing progress for an HTTP download

The current release of Casablanca does not support progress reporting when reading from an HTTP stream, you only know when it’s completed – but, you can read chunk by chunk and get a percentage based on the total size that you can get off the header. Here’s a code snippet that shows one way of doing this with PPL tasks. It recursively calls the Repeat function until there’s nothing left to read, and the then() code in the original call is executed. So you still get a completed event while also being able to report progress. The code snippet does not do anything with the data, it just shows a percentage.

concurrency::task<void> Repeat(
  istream bodyStream, size_t chunkSize, 
  size_t lenRead, size_t contentLength)
{
	container_buffer<std::string> buffer;

	return concurrency::create_task(
    [=] { return bodyStream.read(buffer, chunkSize).get(); })
		.then([=](int bytesRead)
	{
		if(bytesRead > 0)
		{
			std::wcout << (lenRead + bytesRead) * 100 / contentLength 
                 << L"% downloaded"  << std::endl;
			return Repeat(bodyStream, chunkSize, lenRead + bytesRead, contentLength);
		}

		return concurrency::create_task([]{});
	});
}

// . . .

http_client client(L"http://www.codeproject.com");

client.request(methods::GET).then([](http_response response)
{
  if(response.status_code() == status_codes::OK)
  {
    auto bodyStream = response.body();		

    size_t contentLength = response.headers().content_length();
    std::wcout << L"Content length: " << contentLength << std::endl;            

    Repeat(bodyStream, 8192, 0, contentLength).then([]
    {
      std::wcout << L"Completed." << std::endl;            
    });
  }
});

Here’s some sample output:

Content length: 79025
3% downloaded
13% downloaded
17% downloaded
27% downloaded
31% downloaded
41% downloaded
42% downloaded
52% downloaded
58% downloaded
68% downloaded
68% downloaded
79% downloaded
79% downloaded
89% downloaded
91% downloaded
100% downloaded
Completed.

I am not a PPL expert so if you notice anything quirky about this, feel free to comment on it. Thanks.

Casablanca – JSON POST code snippet

Continuing on with Casablance, here’s a code snippet that shows how to POST JSON data to a web server.

json::value postData;
postData[L"name"] = json::value::string(L"Joe Smith");
postData[L"sport"] = json::value::string(L"Baseball");

http_client client(L"http://localhost:5540/api/values");

client.request(methods::POST, L"", postData.to_string().c_str(), 
  L"application/json").then([](http_response response)
{
  std::wcout <<  response.status_code() << std::endl;

  if(response.status_code() == status_codes::OK)
  {
    auto body = response.extract_string();		

    std::wcout << body.get().c_str();
  }
});

C++ does not have reflection, so unlike with .NET, you need to manually create the JSON from an object structure (which may seem like too much work if you’ve used JSON libraries in C# where the JSON is easily auto-generated using reflection). But it should not be too difficult to come up with some helper classes/methods that’ll make this easier for you.

Casablanca code snippets – getting and parsing JSON data

Casablanca is very easy to get started with if you’ve used PPL tasks before, and even if you haven’t it’s still fairly straightforward to use. Here’s an example showing how easy it is to make a GET request to a webserver and to extract the response as a string.

http_client client(L"http://localhost:5540/api/values");

client.request(methods::GET).then([](http_response response)
{
  if(response.status_code() == status_codes::OK)
  {
    auto body = response.extract_string().get();		
    std::wcout << body;
  }
});

The test service I was playing with returned JSON data, and Casablanca has classes to handle JSON too.

[
   {
      "Id":1,
      "Name":"Nish",
      "Sport":"Tennis"
   },
   {
      "Id":2,
      "Name":"Andrew",
      "Sport":"Baseball"
   }
]

Here’s an example showing how the JSON data can be parsed out.

http_client client(L"http://localhost:5540/api/values");

client.request(methods::GET).then([](http_response response)
{
  if(response.status_code() == status_codes::OK)
  {
    response.extract_json().then([](json::value jsonValue)
    {
      for(auto iterArray = jsonValue.cbegin(); iterArray != jsonValue.cend(); ++iterArray)
      {
        const json::value &arrayValue = iterArray->second;

        for(auto iterInner = arrayValue.cbegin(); iterInner != arrayValue.cend(); ++iterInner)
        {
          const json::value &propertyName = iterInner->first;
          const json::value &propertyValue = iterInner->second;

          std::wcout 
            << L"Property: " << propertyName.as_string() 
            << L", Value: " << propertyValue.to_string() 
            << std::endl;

        }		

        std::wcout << std::endl;
      }
    });
  }
});

I hope to publish more Casablanca code samples/snippets on this blog, just FYI.

Setting VC++ up to use Casablanca

Once you’ve installed Casablanca, you’ll need to add the required include/lib folders to your VC++ projects. I took the same approach used by the sample projects.

Open Project Properties / Configuration Properties / C/C++ / General and add the following entry to the Additional Include Directories. (note: line breaks added for formatting)

$([MSBuild]::GetRegistryValue(
`HKEY_LOCAL_MACHINE\Software\Microsoft\Casablanca\OpenSourceRelease\110\SDK`, 
`InstallDir`))\include

Open Project Properties / Configuration Properties / Linker / General and add the following entry to the Additional Library Directories (separate ones for Debug and Release configs). (note: line breaks added for formatting)

$([MSBuild]::GetRegistryValue(
`HKEY_LOCAL_MACHINE\Software\Microsoft\Casablanca\OpenSourceRelease\110\SDK`,
`InstallDir`))\lib\x86\Debug\
$([MSBuild]::GetRegistryValue(
`HKEY_LOCAL_MACHINE\Software\Microsoft\Casablanca\OpenSourceRelease\110\SDK`,
`InstallDir`))\lib\x86\Release\

Now add casablanca110.lib to the Linker / Input / Additional Dependencies.

You’re all set at this point.