禁止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 @   [Blowfish]  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示