Skip to content

Commit 5283148

Browse files
committed
Cast operator overhaul
1 parent 7c954cf commit 5283148

5 files changed

Lines changed: 51 additions & 43 deletions

File tree

‎cmake/multi_file/CMakeLists.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
cmake_minimum_required(VERSION 3.0)
1+
cmake_minimum_required(VERSION _3.0)
22
file(GLOB SOURCES RELATIVE ${CMAKE_SOURCE_DIR} "*.c")
33
add_executable(main ${SOURCES})

‎cpp/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@
2424
1. [Value category cheatsheet](https://github.com/jeaye/value-category-cheatsheet/tree/14aef17fb5ab9c35416ec62ac0d45eb12729901f/resources/code)
2525
1. [Function](function.cpp)
2626
1. [Operator overload](operator_overload.cpp)
27+
1. [Cast operator](cast_operator.cpp)
2728
1. [Default parameters](default_parameters.cpp)
2829
1. [Parameter without name](parameter_without_name.cpp)
29-
1. [Conversion function](conversion_function.cpp)
3030
1. [Lambda](lambda.cpp)
3131
1. [Trailing return type](trailing_return_type.cpp)
3232
1. [explicit](explicit.cpp)

‎cpp/cast_operator.cpp‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/*
2+
Allows to convert objects to primitives and other objects.
3+
4+
http://en.cppreference.com/w/cpp/language/cast_operator
5+
*/
6+
7+
#include "common.hpp"
8+
9+
class ToInt {
10+
public:
11+
int i;
12+
ToInt(int i) : i(i) {}
13+
operator int() {
14+
return this->i;
15+
}
16+
};
17+
18+
class ToToInt {
19+
public:
20+
int i;
21+
ToToInt(int i) : i(i) {}
22+
operator ToInt() {
23+
return ToInt(this->i);
24+
}
25+
};
26+
27+
int main() {
28+
// Explicit cast.
29+
assert((int)ToInt(0) == 0);
30+
31+
// Implicit conversion.
32+
assert(ToInt(0) == 0);
33+
34+
// ERROR: Only a single implicit cast is possible at a time.
35+
//assert(ToToInt(0) == 0);
36+
37+
// OK, on implicit cast.
38+
assert((ToInt)ToToInt(0) == 0);
39+
40+
// OK, all explicit.
41+
assert((int)(ToInt)ToToInt(0) == 0);
42+
}

‎cpp/conversion_function.cpp‎

Lines changed: 0 additions & 41 deletions
This file was deleted.

‎cpp/unique_ptr.cpp‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,13 @@ int main() {
7474
manual_ptr_test();
7575
assert(Base::count == 10);
7676

77+
// Convert to raw pointer.
78+
// Not possible.
79+
{
80+
std::unique_ptr<int> p(new int);
81+
//int *raw = p;
82+
}
83+
7784
// Copy constructor is deleted.
7885
// This is what imposes uniqueness.
7986
{

0 commit comments

Comments
 (0)