Scribbling

[C++] 전문가를 위한 C++ - Chapter 1 본문

Computer Science/C++

[C++] 전문가를 위한 C++ - Chapter 1

focalpoint 2023. 9. 15. 23:51

 

1. import

C++20 has a new feature called "module" - replacing the conventional header file mechanism.

#pragma once
import <iostream>;
import <array>;
import <vector>;


int main() {
	
	std::cout << "Hello World" << std::endl;
}

If you have trouble with "Importing modules" in Visual Studio, https://stackoverflow.com/questions/64877559/cant-use-iostream-as-module-in-c20-visual-studio

 

Can't use iostream as module in C++20 (Visual Studio)

I can't get this code running in the newest version of MSVC. This code example is from the book called "Beginning C++20, From Novice to Professional" by Ivor Horton and Peter Van Weert. i...

stackoverflow.com

 

2. Format

format is very similar to Python formats.

#pragma once
import <iostream>;
import <format>;


int main() {
	
	std::cout << std::format("format example: {}", 29) << std::endl;
}

 

3. numeric_limits

numeric_limits in <limits> provides numeric limits.

int main() {
	
	std::cout << std::numeric_limits<int>::max() << std::endl;
	std::cout << std::numeric_limits<int>::min() << std::endl;
}

 

4. Zero Initializer

int main() {
	
	float float1{};
	int int1{};

	int* intptr1{};

	std::cout << float1 << std::endl;
	std::cout << int1 << std::endl;
	std::cout << intptr1 << std::endl;

}

 

5. Three-way comparison operator

int main() {
	
	int i{ 29 };

	strong_ordering result{ i <=> 29 };
	cout << (result == strong_ordering::less) << endl;
	cout << (result == strong_ordering::greater) << endl;
	cout << (result == strong_ordering::equal) << endl;

}

 

6. Optional

optional<int> func1(bool flag) {
	if (flag) {
		return 29;
	}
	return nullopt;
}

int main() {
	
	optional<int> ret = func1(true);
	if (ret) {
		cout << ret.value() << endl;
	}

}

 

7. Designated Initializer

struct Employee {
	char firstInitial;
	char lastInitial;
	int employeeNumber;
	int salary{ 75000 };
};

int main() {

	Employee employee{
		.firstInitial = 'H',
		.lastInitial = 'C',
		.employeeNumber = 0,
		.salary = 200000,
	};

}

 

8. constexpr

C++ has a constant expression; constant expressions are evaluated during compile time.

constexpr int getInt() { return 29; }

int main() {

	int array[getInt()];

}