blog.michal-wt.com

Once again about C++23

16.12.2022 20:39 dev

It’s very difficult for me to test new features of the new C++ standards on compilers that supports them poorly. For all of my C++ articles I test and try to implement examples containing new things. For this purpose I frequently build weekly snapshots of GCC.
This review contains a small overview of another new things. All of them with my tested examples.



New preprocessor instructions

I dream of the-end of preprocesor instructions in C++, but they ads new.

  • #elifdef – is euqivalent of #elif defined()
  • #elifndef – is equivalent of #elif not defined()
  • #warning "my warning message" – by this instruction we can put some warning messages during compilation.


Byteswap

This solution reverses byte order in your data. For this example let’s take the number 62090 assigned to 16-bit (2 byte) unsigned integer.

62090 in binary system: 1111001010001010 – first byte of this number: 11110010, second byte: 10001010.
Reversed value of this uint:
1000101011110010 (binary) and 35570(decimal).


#include <bit>
#include <iostream>
#include <bitset>


int main() {
	uint16_t num1{62090};
	std::cout << "decimal: " << num1 << ", binary:" << std::bitset<16>(num1)
	<< "\n[Reversed byte order]\ndecimal" << std::byteswap(num1) << ", binary:" 
	<< std::bitset<16>(std::byteswap(num1)) << std::endl;
}

Output:

decimal: 62090, binary:1111001010001010
[Reversed byte order]
decimal 35570, binary:1000101011110010


std::to_underlying

This function gives us possibility to cast enumerated values into integer. Previously, it was possible in the old-school C style.


#include <iostream>
#include <utility>

enum class Size {
	Small = 1,
	Midium = 4,
	Big = 8,
	Large = 16
};

int main() {
	int big = (int) Size::Big;
	std::cout << big << std::endl;
	
	int large{std::to_underlying(Size::Large)};
	std::cout << large << std::endl;
}

Output:

8
16


That’s all now, I want to come back to this subject next year and I hope that the new standard will be better supported by GCC. I hope you read the previous article about C++ 23, if not, do so. ;)
See you on the next article! :)

Mistakes or problems? Do you have any suggestions? Leave a comment, and I will fix it! Sometimes, my English leaves a little to be desired. I'm still learning! :)

Comments