禁止C++的函数返回值进行编译器的隐式类型转换

目的是禁止将int、long等整数类型被编译器悄悄地转换为bool类型,造成潜在的错误。

需要用C++ 20的concept特性。

 

#include <iostream>


//typedef long HRESULT;
using HRESULT = long;
#define S_OK ((HRESULT)0)

#ifdef __cpp_concepts
    #include <type_traits>
    
    template<typename T>
    concept IsBoolean = std::same_as<T, bool>;    

    template<typename T>
    concept IsHRESULT = std::same_as<T, HRESULT>;

    #define bool_t IsBoolean auto
    #define hresult_t IsHRESULT auto
#else
    #define bool_t bool
    #define hresult_t HRESULT
#endif

bool_t TestFunction() {
    return true;
}

hresult_t TestFunction2() {
    return S_OK;
}

hresult_t TestFunction3() {
    return (long)1;
}

int main() {
    auto result = TestFunction();
    auto result2 = TestFunction2();
    std::cout << result2 << ", " << std::boolalpha << result << std::endl;
    return 0;
}

 

posted @ 2024-05-13 16:56  [Blowfish]  阅读(14)  评论(0编辑  收藏  举报