Adding two numbers in modern C++

This morning a friend asked me how to add two numbers in modern C++.
First I wanted to write that you do it as in old C++, but after a little thinking I came up with this example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstdint>

// using is a replacement for typedef
// https://en.cppreference.com/w/cpp/language/type_alias
using int32 = std::int32_t;
using int64 = std::int64_t;

int main()
{
    
    int32 a = 1'000'000;
    // binary-literal https://en.cppreference.com/w/cpp/language/integer_literal
    int32 b = 0b0000'1111; 
    
    int64 c = a + b;
    
    std::cout << "c = " << c << '\n';
} 


Does anyone have more ideas?
I reckon there's a need to harness modern C++ templates in there.
https://en.wikipedia.org/wiki/Roman_numerals
std::cout << "Let's party like it's " << Roman("MCM") + Roman("XCIX") << std::endl;
Thanks for your input.
int64 c = a + b;
Note that if the addition would overflow 32-bit integer values you would only be assigning the overflowed value to the 64-bit integer. If you want to prevent the overflow you need to convert before the addition.
Thanks for the info helios
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <cstdint>

using int32 = std::int32_t;
using int64 = std::int64_t;

constexpr long double operator""_deg(long double deg)
{
    return deg * 3.14159265358979323846264L / 180;
}

template<typename ...Args>
int64 sum(Args ...args)
{
    return (static_cast<int64>(args) + ...);
}

int main()
{
    int32 a = 1'000'000;
    int32 b = 0b0000'1111; 
    int32 c = 120.0_deg * 1000;

    std::cout << sum(a, b, c) << '\n';
} 

Topic archived. No new replies allowed.