example2_conditional_except.cpp

 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
26
#include <iostream>
#include <type_traits>
#include <utility>
#include <string>

template<typename T>
void conditionalFunction(T&& t) noexcept(std::is_nothrow_move_constructible<T>::value) {
    // Properly handle lvalues and rvalues
    T temp = std::forward<T>(t);
    std::cout << "Conditional noexcept: " << std::boolalpha << noexcept(T(std::forward<T>(t))) << std::endl;
}

int main() {
    int x = 10;
    conditionalFunction(x);  // x is an lvalue

    std::string str = "Hello";
    conditionalFunction(str);  // str is an lvalue

    conditionalFunction(20);  // 20 is an rvalue

    std::string rstr = "World";
    conditionalFunction(std::move(rstr));  // std::move(rstr) is an rvalue

    return 0;
}
Back to noexcept