Tuesday, August 29, 2017

C++11: Time: Durations

Durations can only be set with whole numbers. For example, to specify a 1.5 second duration, you need to specify 1500 milliseconds.


C++11: Time: Durations

C++11 has new duration types that can be used with the new time functions.

#include <chrono>
#include <iostream>

int main()
{
  std::chrono::nanoseconds  ns(9'000'000);
  std::chrono::microseconds us(60'000);
  std::chrono::milliseconds ms(300);
  std::chrono::seconds       s(1);

  std::chrono::high_resolution_clock::duration hrc_duration = s + ms + us + ns;

  double hrc_seconds = double(hrc_duration.count())                    *
                       std::chrono::high_resolution_clock::period::num /
                       std::chrono::high_resolution_clock::period::den;  

  std::cout << hrc_seconds << std::endl;

  return 0;
}
// Output: 1.369
Reference: http://en.cppreference.com/w/cpp/chrono/duration

C++11: Time

Three time systems were added. Here is an example:

#include <chrono>
#include <ctime>
#include <iostream>

int main()
{
////
  std::chrono::system_clock::time_point syc_now      = 
                                         std::chrono::system_clock::now();
  std::chrono::system_clock::time_point syc_default  ;
  std::chrono::system_clock::duration   syc_duration = syc_now -
                                                              syc_default;

  double syc_seconds = double(syc_duration.count())           *
                       std::chrono::system_clock::period::num /
                       std::chrono::system_clock::period::den; 

  std::cout << syc_seconds << std::endl;
////
  std::chrono::steady_clock::time_point stc_now     =                                             std::chrono::steady_clock::now();
  std::chrono::steady_clock::time_point stc_default ;
  std::chrono::steady_clock::duration   stc_duration = stc_now -
                                                            stc_default;

  double std_seconds = double(stc_duration.count())           *
                       std::chrono::steady_clock::period::num /
                       std::chrono::steady_clock::period::den;  

  std::cout << std_seconds << std::endl;
////
  std::chrono::high_resolution_clock::time_point hrc_now      =                                   std::chrono::high_resolution_clock::now();
  std::chrono::high_resolution_clock::time_point hrc_default  ;
  std::chrono::high_resolution_clock::duration   hrc_duration = 
                                                   hrc_now - hrc_default;

  double hrc_seconds = double(hrc_duration.count())                    *
                       std::chrono::high_resolution_clock::period::num /
                       std::chrono::high_resolution_clock::period::den;  

  std::cout << hrc_seconds << std::endl;
////
  std::time_t tt_now = std::time(nullptr);

  std::cout << tt_now << std::endl;
  return 0;
}
/* Output:
     1.50396e+09
     33785.6
     33785.6
     1503960804
*/
Reference: http://www.cplusplus.com/reference/chrono/

C++11: Regex: Replacements

You can do regex replacements. Here is an example:

#include <iostream>
#include <regex>
#include <string>

int main(int argc, char * argv[])
{
  std::string   myString("abcdef");
  std::smatch   myMatches;
  std::regex    myRegex("(a)(b)(c)(d)(e)(f)");

  std::cout << std::regex_replace(myString, myRegex, "$6-$5-$4-$3-$2-$1")
            << std::endl;
  return 0;
}
// Output: f-e-d-c-b-a
Reference: http://www.cplusplus.com/reference/regex/regex_replace/

C++11: Regex: Grep

You can use the regex facilities like grep. Here is an example:

#include <fstream>
#include <iostream>
#include <regex>
#include <string>

int main(int argc, char * argv[])
{
  if (argc != 3)
  {
    std::cerr << "Usage: grep <regex> <filename>" << std::endl;
    exit(1);
  }

  std::string   myString;
  std::smatch   myMatches;
  std::regex    myRegex(argv[1]);
  std::ifstream ifs(argv[2]);

  if (ifs.is_open())
  {
    while (std::getline(ifs, myString))
    {
      std::regex_search(myString, myMatches, myRegex);
      if (myMatches.size() == 1)
      {
        std::cout << myString << std::endl;
      }
    }
  }
  else
  {
    std::cout << "Unable to open file." << std::endl;
  }
  return 0;
}
/* Input:
     grep abc test.txt

   test.txt:
     abc
     def
     defabc
     hij
   
   Output:
    abc
    defabc
*/
Reference: http://www.cplusplus.com/reference/regex/regex_search/

C++11: Regex: Global

You can globally search a string as if using the Perl ‘g’ mode switch. Here is an example.

#include <iostream>
#include <regex>
#include <string>
 
int main()
{
  std::string myString("aeiouaeiouaeiou");
  std::regex  myRegex ("aeiou");
  std::smatch myMatches;
  std::string mySuffix;
  bool        keepLooping = true;
 
  keepLooping = true    ;
  mySuffix    = myString;
 
  while (keepLooping)
  {
    keepLooping = std::regex_search(mySuffix, myMatches, myRegex);
    if (myMatches.size() > 0)
    {
      std::cout << myMatches.size() << " ";
      std::cout << myMatches[0] << std::endl;
    }
    mySuffix = myMatches.suffix();
  }
  return 0;
}
/* Output:
 1 aeiou
 1 aeiou
 1 aeiou
*/
Reference: http://www.cplusplus.com/reference/regex/regex_search/

C++11: Regex

Regular Expressions (Regex) were added to C++11. Here is an example:

#include <iostream>
#include <regex>
#include <string>

int main()
{
  std::string myString("abcdefg");
  std::regex  myRegex ("cde"    );
  std::smatch myMatches;

  std::regex_search(myString, myMatches, myRegex);

  if (myMatches.size() > 0) std::cout << myMatches[0] << std::endl;
  
  return 0;
}
// Output: cde
Reference: http://www.cplusplus.com/reference/regex/regex_search/

C++11: Bind: Overloading

When you are binding with an overloaded function, you need to specify the type of the function. Here is an example:

#include <functional>
typedef int (F)(int);

int    f(int    i) { return 0  ; }
double f(double d) { return 0.0; }

   F    * f1 =              f;
   F    * f2 = (int(*)(int))f;
   F    * f3 = (F   *      )f;
// auto   f4 =              f; // Does not compile
   auto   f5 = (int(*)(int))f;
   auto   f6 = (F   *      )f;

// F    * g1 = std::bind(             f, std::placeholders::_1); // Does not compile
// F    * g2 = std::bind((int(*)(int))f, std::placeholders::_1); // Does not compile
// F    * g3 = std::bind((F   *      )f, std::placeholders::_1); // Does not compile
// auto   g4 = std::bind(             f, std::placeholders::_1); // Does not compile
   auto   g5 = std::bind((int(*)(int))f, std::placeholders::_1);
   auto   g6 = std::bind((F   *      )f, std::placeholders::_1);

int main()
{
    return 0;
}
Reference: https://isocpp.org/wiki/faq/cpp11-library#std-function

C++11: Bind: Currying

The binding of arguments is also know as currying.


C++11: Bind: Placeholders

The placeholder objects (_1, _2, …) map the ‘new function’ parameters to ‘old function’ parameters. _5 represents the fifth argument of the ‘new function’.

Tuesday, August 22, 2017

C++11: bind

The template std::bind was added. It allows you to created a function wrapper that binds some of the arguments.

#include <functional>
#include <iostream>

int add(int lhs, int mhs, int rhs) {return lhs + mhs + rhs;}

int main()
{
  auto f_add_0 = std::bind(
                        add                  ,
                        std::placeholders::_1,
                        std::placeholders::_2,
                        std::placeholders::_3);

  auto f_add_1 = std::bind(
                        add                  ,
                        std::placeholders::_1,
                        std::placeholders::_2,
                        10                   );

  auto f_add_2 = std::bind(
                        add                  ,
                        std::placeholders::_1,
                        10                   ,
                        100                  );

  auto f_add_3 = std::bind(
                        add                  ,
                        1                    ,
                        10                   ,
                        100                  );
  
  std::cout << f_add_0(1, 2, 3) << " " <<
               f_add_1(1, 2   ) << " " <<
               f_add_2(9      ) << " " <<
               f_add_3(       ) << " " << std::endl;
  return 0;
}
// Output: 6 13 119 111
Reference: http://en.cppreference.com/w/cpp/utility/functional/bind

C++11: function

The template std::function was added. It allows you to wrap functions. Here is an example:

#include <functional>
#include <iostream>

int add(int lhs, int rhs) {return lhs + rhs;}

int main()
{
  std::function<int(int,int)> f_add = add;

  std::cout << f_add(1, 2) << std::endl;
  return 0;
}
// Output: 3
Reference: http://en.cppreference.com/w/cpp/utility/functional/function

C++11: type traits

Several new type traits were added to the language. Type traits are defined in the header file. The purpose of type traits is to get or set the properties of types.” Here is a list of added Primary type categories to C++11:

is_void
is_integral
is_floating_point
is_array
is_enum
is_union
is_class
is_function
is_pointer
is_lvalue_reference
is_rvalue_reference
is_member_object_pointer
is_member_function_pointer
Here is an example:

#include <iostream>
#include <type_traits>

class C {};
enum E {};
union U {};
typedef int MyInt;
typedef double MyDouble;

int main()
{
  std::cout << std::is_class<C>                ::value << " ";
  std::cout << std::is_enum<E>                 ::value << " ";
  std::cout << std::is_union<U>                ::value << " ";
  std::cout << std::is_integral<MyInt>         ::value << " ";
  std::cout << std::is_floating_point<MyDouble>::value << " ";
  std::cout << std::is_class<E>                ::value << " ";
  std::cout << std::is_enum<C>                 ::value << std::endl;

  return 0;
}
// Output: 1 1 1 1 1 0 0
Reference: http://en.cppreference.com/w/cpp/types

C++11: tuple

You can now make ordered lists of mixed types called tuples. Here is an example:

#include <iostream>
#include <string>
#include <tuple>

int main()
{
  std::tuple<char, int, double, const char *, std::string> s;
  std::tuple<char, int, double, const char *, std::string> t;

  s = std::make_tuple('A', 1, 2.5, "three", "four");
  t = std::make_tuple('A', 1, 2.5, "three", "four");

  if (s == t) std::cout << "Tuples Match, ";

  double myDouble = std::get<2>(s);
  std::cout << myDouble << std::endl;

  return 0;
}
// Output: Tuples Match, 2.5
Reference: https://isocpp.org/wiki/faq/cpp11-library#tuple
                  http://en.cppreference.com/w/cpp/utility/tuple

C++11: weak_ptr

A weak_ptr is a kind of pointer that can share access to a pointer, but does not have a say in when the pointed to object is deleted. Here is an example:

#include <iostream>
#include <memory>

int main()
{
  std::shared_ptr<int> sptr1(new int());
  std::shared_ptr<int> sptr2;
  std::weak_ptr<int>   wptr1;

////
  *sptr1 = 4;
  sptr2  = sptr1;
  std::cout << (sptr1?*sptr1:0) << " " << (sptr2?*sptr2:0) << " ";

  wptr1  = sptr1;
  auto sptr3 = wptr1.lock();
  std::cout << (sptr3?*sptr3:0) << std::endl;
  wptr1.reset();
////
  sptr1.reset();
  std::cout << (sptr1?*sptr1:0) << " " << (sptr2?*sptr2:0) << " ";

  wptr1 = sptr2;  
  auto sptr4 = wptr1.lock();
  std::cout << (sptr4?*sptr4:0) << std::endl;
  wptr1.reset();
////
  sptr2.reset();
  std::cout << (sptr1?*sptr1:0) << " " << (sptr2?*sptr2:0) << " ";

  wptr1 = sptr2;
  auto sptr5 = wptr1.lock();
  std::cout << (sptr5?*sptr5:0) << std::endl;
  wptr1.reset();
////
  return 0;
}
/* Output:
4 4 4
0 4 4
0 0 0
*******/
Reference: https://isocpp.org/wiki/faq/cpp11-library#weak-ptr

C++11: shared_ptr

You can safely share a pointer using shared_ptr. Here is an example:

#include <iostream>
#include <memory>

int main()
{
  std::shared_ptr<int> ptr1(new int());
  std::shared_ptr<int> ptr2;

  *ptr1 = 4;
  ptr2  = ptr1;

  std::cout << (ptr1?*ptr1:0) << " " << (ptr2?*ptr2:0) << " ";

  ptr1.reset();
  std::cout << (ptr1?*ptr1:0) << " " << (ptr2?*ptr2:0) << " ";

  ptr2.reset();
  std::cout << (ptr1?*ptr1:0) << " " << (ptr2?*ptr2:0) << std::endl;

  return 0;
}
// Output: 4 4 0 4 0 0
Reference: https://isocpp.org/wiki/faq/cpp11-library#shared-ptr

C++11: unique_ptr

You can ensure that there is only one owner of a pointer using unique_ptr. Here is an example:

#include <iostream>
#include <memory>

int main()
{
  std::unique_ptr<int> ptr1(new int());
  std::unique_ptr<int> ptr2;

  *ptr1 = 4;
  ptr2  = std::move(ptr1);

  std::cout << (ptr1?*ptr1:0) << " " << (ptr2?*ptr2:0) << std::endl;
  return 0;
}
// Output: 0 4
Reference: https://isocpp.org/wiki/faq/cpp11-library#unique-ptr

C++11: __STDC_HOSTED__ Macro

If __STDC_HOSTED__ is defined as 1 by the compiler, then the all of the C standard library facilities are available.


                    https://isocpp.org/wiki/faq/cpp11-language-misc#cpp11-c99

C++11: Empty Macro

You can now define a macro that takes arguments and expands to nothing. Here is an example:

#define LOG(X)
Reference: https://stackoverflow.com/questions/9187628/empty-function-macros
                  https://isocpp.org/wiki/faq/cpp11-language-misc#cpp11-c99

C++11: Variadic Macros

You can define Macros that take an arbitrary number of arguments. Here is an example:

#include <cstdio>
#define REPORT(...) printf(__VA_ARGS__);

int main()
{
  REPORT("%s %s %s\n", "ME", "MYSELF", "I");
  return 0;
}
// Output: ME MYSELF I

Reference: https://isocpp.org/wiki/faq/cpp11-language-misc#cpp11-c99

Wednesday, August 16, 2017

C++11: C99 Features: _Pragma

A functional form of pragma was added. _Pragma( X ) expands to #pragma X
This does not work on Microsoft Visual Studio 2015.  You need to replace _Pragma with __pragma


C++11: C99 Features: __func__

The macro __func__ was added, so that you could get the string of the current function. This is useful for trace statements.


C++11: Alignment

You can use the alignof() function to get the alignment (in number of bytes) of a type. Here is an example:
constexpr int intAlignmentInBytes = alignof(long long);


C++11: Alignment

You can specify the alignment of arrays with the alignas() operator. Previously, if you allocated bytes, you could not guarantee the alignment, which caused exceptions when the bytes were used as raw memory to back larger data types. Here is an example:
alignas(double) unsigned char buffer[1024];


C++11: Attributes

Attributes where added to C++11. They are contained within double square brackets: [[…]]. The double brackets can have spaces between them. The attributes come right after the entity they modify.  The attributes can be future C++ options, or vendor-specific options.


C++11: Raw String Literals

If you have a lot of characters that need to be escaped, you can use raw string literals to simplify a string. Here is an example:

#include <iostream>
int main()
{
  std::cout << R"(\\\\\)" << std::endl;
  return 0;
}
// Output: \\\\\
Reference: https://isocpp.org/wiki/faq/cpp11-language-misc#raw-strings

C++11: Static Assertion


static_assert(<bool_constexpr> , <message>); was added to c++11.
Here is an example:

static_assert( (sizeof(long) == 3), "Error: the type int is not 3 bytes");
int main() {return 0;}
// Output During Compile: error C2338: Error: the type int is not 3 bytes

Reference: https://isocpp.org/wiki/faq/cpp11-language-misc#static-assert
                  http://en.cppreference.com/w/cpp/language/static_assert

C++11: Local Types as Template Arguments

Local and Unnamed types can now be used as template arguments.


C++11: Variadic Templates

Variadic Parameters were added to Templates.

#include <iostream>

template<class ... Ts>
void f(Ts ... args)
{
  const int size = sizeof...(args) + 1;
  int res[size] = {1, args...};

  std::cout << "------" << std::endl;
  for (int i = 1; i < size; i++)
  {
    std::cout << res[i] << std::endl;
  }
}

int main()
{
  f();
  f(1);
  f(1, 2);
  f(1, 2, 3);
  return 0;
}
/* Output:
------
------
1
------
1
2
------
1
2
3
*******/

References: https://isocpp.org/wiki/faq/cpp11-language-templates#variadic-templates
                    http://en.cppreference.com/w/cpp/language/parameter_pack

C++11: Template Aliases

You can create Template that renames another template, but with some template parameters filled in. Here is an example:

template<class T, class U, class V>
struct MyTemplate {T t; U u; V v;};

template<class T>
using MyTemplateUV =  MyTemplate<T, int, float>;

MyTemplateUV<int>           s = {1, 2, 3.0};
MyTemplate  <int,int,float> t = {4, 5, 6.0};

int main()
{
  t = s;
  return 0;
}

Reference: https://isocpp.org/wiki/faq/cpp11-language-templates#template-alias

Monday, August 7, 2017

C++11: Suffix Return Type Syntax


The following function:
      int function();
Can also be written like:
      auto function() -> int;
Reference: https://isocpp.org/wiki/faq/cpp11-language-misc#suffix-return

C++11: Right-angle Brackets


list<vector<string>> lvs; works
Reference: https://isocpp.org/wiki/faq/cpp11-language-misc#right-angles

C++11: Preventing narrowing

{} initialization doesn’t narrow

C++11: The value of __cplusplus

The value of __cplusplus for C++11 is 20113L.

C++11: Extern templates

Templates can be declared as extern, so that they are redundantly specialized.

C++11: PODs (Plain Old Data)

POD data lets you interoperate with C. The binary layout are compatible. C++11 PODs do not matter on whether or not you have constructors.

C++11: Unions: Members with CTORs and DTORs

Unions can now allow members with CTORs and DTORs. They are marked deleted by the compiler.

C++11: long long

A long long type is an integer that is at least 64-bits long. A long type can be less than 64-bits.

C++11: enum class: Underlying Type

You can specify the underlying type of an enum class. Here is an example:

#include <iostream>
enum       EnumDefault                   {A, B};
enum       EnumChar          : char      {C, D};
enum       EnumShort         : short     {E, F};
enum       EnumInt           : int       {G, H};
enum       EnumLongLong      : long long {I, J};
 
enum class EnumClassDefault              {A, B};
enum class EnumClassChar     : char      {C, D};
enum class EnumClassShort    : short     {E, F};
enum class EnumClassInt      : int       {G, H};
enum class EnumClassLongLong : long long {I, J};
 
int main()
{
  std::cout << sizeof(EnumDefault      ) << " " <<
               sizeof(EnumChar         ) << " " <<
               sizeof(EnumShort        ) << " " <<
               sizeof(EnumInt          ) << " " <<
               sizeof(EnumLongLong     ) << " " <<
 
               sizeof(EnumClassDefault ) << " " <<
               sizeof(EnumClassChar    ) << " " <<
               sizeof(EnumClassShort   ) << " " <<
               sizeof(EnumClassInt     ) << " " <<
               sizeof(EnumClassLongLong) << std::endl;
  return 0;
}
// Output: 4 12 4 8 4 1 2 4 8
Reference: https://isocpp.org/wiki/faq/cpp11-language-types#enum-class

C++11: enum class

enum classes do not get implicitly converted to an integer. enum classes are scoped. Here is an example:

enum Alpha {A, B, C};
enum class Beta {X, Y, Z};
int main()
{
    Alpha alpha = A;
    Beta  beta  = Beta::X;
    int   alpha_int = alpha;
    int   beta_int  = static_cast(beta); // Cast is necessary in order to compile.
    return 0;
}
Reference: https://isocpp.org/wiki/faq/cpp11-language-types#enum-class