The choice between typename and class

When working with C++ templates, you have probably seen typename and class used interchangeably. Is there a difference between them? This post will explain when these two keywords can be used in templates. Let’s consider the following example: In this context, when declaring a type template parameter, there is no difference, they are interchangeable. They … Read more

When a type is not a type

This article has been updated for C++20.

Let’s take a look at the following code sample:

template <typename T> 
struct foo
{
   foo(T) {}
};

int main()
{
   std::pair   p{ 1, "one" };
   std::vector v{ 1, 2 };
   foo         f{ 42 };
}

Here, p is a std::pair, v is a std::vector, and f is a foo. But there is no such thing as a std::vector type (nor std::pair or foo). std::vector<int> is a type, and std::vector<T> is a type template, but std::vector is just a placeholder that activates a C++17 feature called class template argument deduction (which we will call CTAD for short).

Read more

Five examples for avoiding the preprocessor

The C++ preprocessor is a text replacement tool used to transform the source code in order to produce a single text file that is then passed to the actual compiler. It has various capabilities, such as including files, conditional compilation, text macro replacement, error emitting, stringizing, or token concatenation. Often developers use the preprocessor when other alternatives are available and are more appropriate. In this article, I will show five examples of when and how you can avoid the use of the preprocessor.

Read more

T4 Lessons Learned

Working with T4 recently I learned a couple of valuable lessons I’d like to share. Lesson 1: Template Language One of the parameters of the language directive is the language, which specifies the language used in the code blocks of the template. Two languages are specified, C# and VB. <#@ template language=”C#” #> However, any … Read more