c++ true_type与false_type

std::true_type和std::false_type

实际上是类型别名

是两个类型(类模板)

注意区分true_type与false_type与true和false区别

  • true_typefalse_type代表类型

  • true,false代表值

nmsp1::FalseType myfunc1();//返回假这种含义
nmsp1::TrueType myfunc2();//返回真这种含义

自己模拟实现

namespace nmsp1 {
    template<bool val>
    struct BoolConstant {
        using type = BoolConstant<val>;

        static constexpr bool value = val;
    };

    using TrueType = BoolConstant<true>;
    using FalseType = BoolConstant<false>;


    template<typename T,bool val>
    struct AClass
    {
        AClass() {
            cout << "AClass()执行了" << endl;
            //if(val) {
            //    T tmpa = 15;
            //}
            //else {
            //    T tmpa = "abc";    //int tmpa = "abc";
            //}

            //if constexpr (val) {
            //    T tmpa = 15;
            //}
            //else {
            //    T tmpa = "abc";    //int tmpa = "abc";
            //}

            AClassEx(BoolConstant<val>());//创建一个临时对象
        }

        void AClassEx(TrueType) {
            T tmpa = 15;
        }
        void AClassEx(FalseType) {
            T tmpa = "abc";
        }

        //当为ture时只会去编译重载版本的TureType
    };
}

nmsp1::AClass<int, true> tmpobj1;
//如果是第一条注释的if语句会报const char[4]无法转换为int
nmsp1::AClass<string, false> tmpobj2;
//如果是第一条注释的if语句会报无法从int转换为string

 

编译器设计时的考量,编译器是能够在编译器时期判断出来执行AClass类模板构造函数的哪个分支的,但从编译出代码这个角度来说,不管是哪个条件分支都会去编译,那么编译false分支就会报错.

if constexpr:属于编译期间if语句,可以解决上面
角度来说,不管是哪个条件分支都会去编译,那么编译false分支就会报错.

if constexpr:属于编译期间if语句,可以解决上面


原文链接:https://blog.csdn.net/m0_51271123/article/details/121780266

posted @ 2024-05-13 15:32  白伟碧一些小心得  阅读(152)  评论(0编辑  收藏  举报