NOTE: Every post ends with "END OF POST". If you don't see it then open the full post in a separate page!

Emulating in, out and inout function parameters – Part 2

Emulating in, out and inout function parameters in C++.

This is the continuation of Part 1 of this post.

In Part 1, we created classes to represent Input, Output and Input-Output parameters and arguments.
Here is an example how those classes can be used:

#include "param_inout.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace param_inout;
using namespace std;
#define PRINT(arg) cout << __FUNCTION__ << ":" << __LINE__ << ": "<< arg << " " << endl

double func1(inp<int> p) {
    // p = 1; // Error: p is read-only.
    return p * 2.2;

void func2(outp<int> p) {
    // int a = p; // Error: p is write-only.
    p = 88;

void func3(inoutp<string> p) {
    auto t = string(p); // p is readable.
    p = "Hello ";       // p is writable.
    p = string(p) + t;  // p is readable and writable.

void func4(inp<string> pattern,
           inp<vector<string>> items,
           inoutp<string> message,
           outp<int> matchCount) {
    auto& ritems = items.arg();
    matchCount = count_if(begin(ritems), end(ritems),
        [&](const string& a) { return a.find(pattern) != string::npos; });
    message = "Done";

void func5(inp<int> p1, outp<int> p2, inoutp<string> p3) {
    // func1(p1); // Error! Good! inp::inp(const inp&) is private.

int main() {
    // auto a = func1(ina(2.2)); // Error: Cannot convert ina<double> to ina<int>
    // auto a = func1(2); // Error: inp::inp(const int&) is private.
    auto a0 = func1(ina(static_cast<int>(2.2)));   PRINT(a0);
    auto a1 = func1(ina(2));                       PRINT(a1);
    auto a2 = 0;                func2(outa(a2));   PRINT(a2);
    auto a3 = string{"world!"}; func3(inouta(a3)); PRINT(a3);

    auto a4 = vector<string>{"avocado", "apple", "plum", "apricot", "orange"};
    auto a5 = string{"Searching..."};
    auto a6 = 0;
    func4(ina(string{ "ap" }), ina(a4), inouta(a5), outa(a6));
    PRINT(a5);  PRINT(a6);

    func5(ina(5), outa(a6), inouta(a5));  PRINT(a5); PRINT(a6);

    return 0;

This example code produces the following output:

main:47: 4.4
main:48: 4.4
main:49: 88
main:50: Hello world!
func4:30: Searching...
main:56: Done
main:56: 2
main:58: Hello Done
main:58: 88

In the code example above, it is clear at the parameter declaration how each parameter is used by the function. Also, for declaration, we chose the convention to include a trailing “p” after the category. For example, outp signifies an Output Function Parameter. It says that it’s for output and it also says that it’s a parameter (i.e. not an argument).

At the call sites, we pass function arguments using ina (input), outa (output) and inouta (input and output). This way, we can clearly see that they are Function Arguments (not parameters); and how the function is going to use those arguments. No surprises.

It is also obvious how to construct function declarations ourselves. For example, the simple functions at the beginning of this post may be declared like this, regardless who does it:

void f(inoutp<string> s);
void g(inp<string> s);

void caller() {
  auto a1 = string{"hello"};

And our std::vector example will become this:

void f(inp<vector<string>> v);

It is clear what is happening both at the declaration and at the call site. Also, this convention is much easier and obvious to follow.


References about the complexity of function parameter declaration guidelines



Emulating in, out and inout function parameters – Part 1

Emulating in, out and inout function parameters in C++.

In C++, passing arguments to functions can be done in a variety of ways. If you are not careful, even thou your function works as intended, the way its parameters are declared can easily mislead the caller.

Consider the following simple examples:

void f(string *s);
void g(string &s);

void caller() {
  auto a1 = string{"hello"};

Is function f going to change s? Is it so that the writer meant “const char *” but the const qualifier is missing by mistake?
Same applies to function g. Also, when calling g, it is not apparent that it may change a1. It looks like it takes a1 by value.

These and similar issues can be avoided by laying down coding conventions about “how to name functions” and “how to declare function parameters” for your team members in your project. The problem with such guidelines is that it may be hard to follow. Even in simple cases they may not be obvious. For example, we may know that our compiler can copy std::vector by merely copying a pointer. So you automatically declare the input parameter like this:

void f(vector<string> v);

On the other hand, other people may not know this. In this case, they tend to declare the same kind of input parameter like this:

void f(const vector<string>& v);

Both of these are correct but it leads to inconsistency and confusion. Also, guidelines about “how to declare function parameters” can become quite complex considering when and how to use pointers, references, const qualifiers, pass-by-value, etc in function declarations.

99% of the time, we can categorize function parameters as

  • Input: Parameters that are only read by the function. They are not changed.
  • Output: Parameters that are only written by the function. The value of the corresponding argument that the caller passes in is not relevant to the function. These parameters are products of the function and the caller sees their new values when the function returns.
  • Input and output: Parameters that are both read and written by the function.

Some languages, like C#, provide standard tools for specifying these categories for function parameters. C++ does not provide standard tools for this. Fortunately, C++ is a very flexible language and we can roll our own tools to achieve this.

Here is one way to implement such a feature:

#pragma once
namespace param_inout {
    // Input
    template <typename T> class inp;
    template <typename T> inp<T> ina(const T&);
    template <typename T> inp<T> ina(const inp<T>&);
    template <typename T>
    class inp {
        inp(inp&& other) : m_arg{other.m_arg} { /* empty */ }
        operator const T&() const { return m_arg; }
        const T& arg() const { return m_arg; }
        inp(const inp&) = delete;
        inp(const T& arg) : m_arg{arg} { /* empty */ }
        friend inp<T> ina<T>(const T&);
        friend inp<T> ina<T>(const inp<T>& arg);
        const T& m_arg;
    template <typename T>
    inp<T> ina(const T& arg) { return inp<T>{arg}; }
    template <typename T>
    inp<T> ina(const inp<T>& param) { return inp<T>{param.m_arg}; }

    // Output
    template <typename T> class outp;
    template <typename T> outp<T> outa(T&);
    template <typename T> outp<T> outa(outp<T>&);
    template <typename T>
    class outp {
        outp(outp&& other) : m_arg{other.m_arg} { /* empty */ }
        outp& operator=(const T& otherArg) { m_arg = otherArg; return *this; }
        outp(const outp&) = delete;
        outp(T& arg) : m_arg{arg} { /* empty */ }
        friend outp<T> outa<T>(T&);
        friend outp<T> outa<T>(outp<T>&);
        T& m_arg;
    template <typename T>
    outp<T> outa(T& arg) { return outp<T>{arg}; }
    template <typename T>
    outp<T> outa(outp<T>& param) { return outp<T>{param.m_arg}; }

    // Input and output
    template <typename T> class inoutp;
    template <typename T> inoutp<T> inouta(T&);
    template <typename T> inoutp<T> inouta(inoutp<T>&);
    template <typename T>
    class inoutp {
        inoutp(inoutp&& other) : m_arg{other.m_arg} { /* empty */ }
        operator T&() { return m_arg; }
        T& arg() const { return m_arg; }
        inoutp& operator=(const T& otherArg) { m_arg = otherArg; return *this; }
        inoutp(const inoutp&) = delete;
        inoutp(T& arg) : m_arg{arg} { /* empty */ }
        friend inoutp<T> inouta<T>(T&);
        friend inoutp<T> inouta<T>(inoutp<T>&);
        T& m_arg;
    template <typename T>
    inoutp<T> inouta(T& arg) { return inoutp<T>{arg}; }
    template <typename T>
    inoutp<T> inouta(inoutp<T>& param) { return inoutp<T>{param.m_arg}; }

These simple classes wrap around references to the actual function arguments. Why?

  • For Output and Input-Output parameters, taking a reference is necessary since we want to write into the arguments and make those writes visible to the caller.
  • For Input parameters, we take a const reference. It is a reference because most of the time it is “efficient enough”. It is const because it is a reference and we want it to be read-only. If we want, we can specialize it for simple types, like char or int, to store a copy and not a reference. For the sake of consistency and simplicity, even if you choose to specialize it, it’s probably better to always treat inp<T> as a reference. That is, make a copy of its contents (inp<T>.arg()) if you want to save it somewhere after the function returns.

In Part 2 of this post, we look at how these classes can be used.
Continue to Part 2.


Declaration and initialization with auto

Guidelines about the auto keyword of C++11 for variable declaration.

The guidelines around the usage of the auto keyword in C++11 is controversial. One argument is that “auto hides the type”. In practice, I found that this is not a concern, unless you use “notepad.exe” as your IDE. This post lists a collection of examples and guidelines for local variable declaration and initialization with auto.

Initialization in C++ is a mess.

int i;
float f(3.3);
double d = 4.4;
char c = i + 2;
class A {
  A() : s(), i() {}
  string s;
  int i;
string t(); // This is not even a variable declaration!

All the above variables are declared and initialized using different syntax and semantics.
For example, variable i is Default Initialized. In case of int, it is effectively not initialized at all.
Variable f is initialized with 3.3 but it looks more like a function call.
The A::s and A::i variables are Value Initialized, A::i with 0 and A::s with the default constructor of string.
On the other hand, the last one is not a variable definition but a function declaration. The t is a function that takes no arguments and returns a string.
This is anything but consistent. If I was new in C++ land, I would consider this confusing and I may prematurely turn away from learning C++ in favor of some other language. I think it is a pity.

Fortunately with C++11, the language gained a new way of declaring variables. The same code looks like this when using the auto keyword and Braced Initialization:

auto i = 1;
auto f = 3.3f;
auto d = 4.4;
auto c = char{i + 2};
class A {
  A() : s{}, i{} {}
  string s;
  int i;

This looks much more consistent and also safer (see the guidelines at the end of this post).

Here is a more elaborate example about the basic usage:

#include <iostream>
#include <string>
#include <typeinfo>
#include <vector>
#include <memory>
using namespace std;

template<typename T>
void print(const T& a) { cout << typeid(T).name() << "=(" << a.i << "," << a.d << "," << a.s << ") " << endl; }

struct A {
  int i;  double d;  string s;

struct B {
  explicit B(int ai, string as) : i{ai}, s{as} {}
  virtual ~B() {}
  int i;  double d;  string s;

struct C : public B {
  explicit C() : B{1, "C"} {}

int main() {                          // Type of declared variable
                                      // ---------------------------
  auto i1 = 11;                       // int
  auto i2 = 12u;                      // unsigned int
  auto i3 = 13.0f;                    // float
  auto i4 = 13.0;                     // double
  auto i5 = "hello";                  // const char[6]
  auto i6 = string{"hello"};          // string
  // auto i7 = int{i3};               // n/a (Error: narrowing from float to int!)

  auto v1 = vector<int>{};            // vector<int> (empty vector)
  auto v2 = vector<int>{1, 2, 3, 4};  // vector<int> (with elements 1, 2, 3, 4)
  auto p1 = unique_ptr<B>{new C{}};   // unique_ptr<B>
  auto p2 = shared_ptr<B>{new C{}};   // shared_ptr<B>
  auto p3 = new A{};                  // A*
  delete p3;
  auto p4 = static_cast<B*>(new C{}); // B* (Ugly! Good! Discourages polymorphic raw pointers.)
  delete p4;
  // auto a0 = A;                     // n/a (Error: Initialization required! Good!)
  auto a1 = A{};                      // A (Value initialization)
  auto a2 = A{11, 3.3, "A"};          // A (Aggregate initialization)

  // auto b1 = B{};                   // n/a (Error: No such user-defined constructor!)
  auto b2 = B{22, "B"};               // B
  // auto b3 = B{1, 4.4, "B"};        // n/a (Error: No such user-defined constructor!)

  print(a1);  print(a2);
  return 0;

Here is the output of the above program:


There are some situations when determining the resulting type of the declaration may look not so obvious, but it all makes sense and remembering the following helps you out:

  • “auto a = expression;” in general:
    • Creates a new object called a.
    • It has the same type as expression.
    • Initialized with the value of expression.
  • “auto a = expression;”
    • a is a new object. The value of expression is copied into a. So, the CV qualifier of the expression is dropped.
  • “auto& a = referencable_expression;” and
  • “auto* a = pointer_expression;” same as
    “auto a = pointer_expression;”

    • This creates a new reference (a reference or a pointer) to the object returned by the expression. Because it is a reference, the CV qualifier of the
      expression is “inherited” to a. For example, this will create a const reference if the expression itself is const. Makes sense!

Here is an example of some “not so obvious” declarations denoting the source type and the resulting type. Pay attention that the first column is the resulting type and the second column is the source type (the “a <- b" notation indicates that we get type a from type b).

#include <iostream>
#include <typeinfo>
using namespace std;

int main() {
  //                                        Result      Source
  //                                    -----------------------------------
  auto i = int{3};                       // int         <-  int

  auto v1 = i;                           // int         <- int
  const auto v2 = i;                     // const int   <- int
  auto& v3 = i;                          // int&        <- int
  const auto& v4 = i;                    // const int&  <- int
  auto v5 = static_cast<const int>(i);   // int         <- const int
  auto v6 = static_cast<const int&>(v3); // int         <- const int&

  auto& t4 = v4;                         // const int&  <- const int& (CV inherited)
  const auto& t5 = v4;                   // const int&  <- const int&
  auto& t6 = v3;                         // int&        <- int&

  auto w1 = v3;                          // int         <- int&
  auto w2 = v4;                          // int         <- const int&

  auto p1 = &i;                          // int*        <- int*
  auto p2 = p1;                          // int*        <- int*
  const auto p3 = p1;                    // int* const  <- int*
  auto& p4 = p1;                         // int*&       <- int*
  auto q1 = static_cast<const int*>(&i); // const int*  <- const int* (CV inherited)
  auto q2 = q1;                          // const int*  <- const int* (CV inherited)
  auto q3 = *q1;                         // int         <- const int

  auto* r1 = static_cast<const int*>(&i);// const int*  <- const int* (CV inherited)
  auto* r2 = r1;                         // const int*  <- const int* (CV inherited)
  auto* r3 = *r1;                        // int         <- const int

  auto z1 = {1, 2, 3};                   // std::initializer_list<int>

One other important rule to remember is that the Initializer-list Constructor wins over normal constructors. In other words, when in doubt, the compiler picks the Initializer-list Constructor. Here is an example that demonstrates this:

#include <iostream>
#include <string>
#include <typeinfo>
#include <initializer_list>
#include <vector>
using namespace std;

template<typename T>
void print(const T& a) {
  cout << typeid(T).name() << "=(" << a.i << "," << a.d << "," << a.s << ",[";
  for (const auto i : a.v) { cout << i << " "; }
  cout << "])" << endl;

struct D {
  explicit D() {}
  explicit D(initializer_list<int> il) : v{il} {}
  int i;  double d;  string s;  vector<int> v;

struct C {
  explicit C(int ai, string as) : i{ai}, s{as} {}
  explicit C(int ai1, int ai2) : i{ai1 + ai2} {}
  explicit C(initializer_list<int> il) : v{il} {}
  int i;  double d;  string s;  vector<int> v;

int main() {
  auto v1 = vector<int>{};     // Empty vector
  auto v2 = vector<int>{1, 5}; // Vector with values [1, 5]
  auto v3 = vector<int>(1, 5); // Vector with values [1, 1, 1, 1, 1]

  auto d1 = D{};                 // D::D() user-defined
  auto d2 = D{1, 2, 3, 4 ,5, 6}; // D::D(initializer_list<int>)

  auto c1 = C{};                 // C::C(initializer_list<int>), no user-defined C::C()
  // auto c2 = C{33, 4.4, "C"};  // Error:
                                 // Compiler wants C::C(initializer_list<int>)
  auto c3 = C{10, 20};           // C::C(initializer_list<int>)
  auto c4 = C{33, "C"};          // C::C(int, string), compiler cannot deduce init-list
  auto c5 = C{1, 2, 3, 4, 5, 6}; // C::C(initializer_list<int>)

  print(d1);  print(d2);
  print(c1);  print(c3);  print(c4);  print(c5);
  return 0;

Here is the output of this example program:

1D=(-1217352208,-5.02222e-42,,[1 2 3 4 5 6 ])
1C=(-1220249883,4.88997e-270,,[10 20 ])
1C=(-1217346088,4.8697e-270,,[1 2 3 4 5 6 ])


  • Almost Always Auto: Use auto for local variable declaration whenever you can.
    • Safety: Discourages uninitialized variables (Default Initialization).
    • Safety: Discourages using naked pointers (the polymorphic case).
    • Correctness: No automatic narrowing! You get the exact type.
    • Convenience: With auto, the compiler “figures out” the type for you.
    • Convenience: Use standard literal suffixes and prefixes for less typing.
      • Integer suffixes: u (unsigned int), l (long int), ul (unsigned long int).
      • Floating point suffixes: L (long double), f (float).
      • Character prefixes: Lā€™ā€™ (wchar_t), Lā€ā€ (const wchar_t[]).
  • Almost Always Brace Initializers: Use brace initializers whenever you can.
    • Consistency: Provides one syntax for initialization.
    • Initialization != Function call != Type cast
      • “auto w = Widget(12)”: This looks like a function call, but it’s not. It is a type cast of int to Widget (Explicit Type Conversion).
      • “auto w = Widget{12}”: This looks like a brace initializer and it is a brace initializer.
  • Almost: The compiler will tell you when you cannot use auto.