std::enable_if to conditionally compile a member function

前端 未结 7 2198
执笔经年
执笔经年 2020-11-22 04:57

I am trying to get a simple example to work to understand how to use std::enable_if. After I read this answer, I thought it shouldn\'t be too hard to come up wi

7条回答
  •  滥情空心
    2020-11-22 05:29

    I made this short example which also works.

    #include 
    #include 
    
    class foo;
    class bar;
    
    template
    struct is_bar
    {
        template
        typename std::enable_if::value, bool>::type check()
        {
            return true;
        }
    
        template
        typename std::enable_if::value, bool>::type check()
        {
            return false;
        }
    };
    
    int main()
    {
        is_bar foo_is_bar;
        is_bar bar_is_bar;
        if (!foo_is_bar.check() && bar_is_bar.check())
            std::cout << "It works!" << std::endl;
    
        return 0;
    }
    

    Comment if you want me to elaborate. I think the code is more or less self-explanatory, but then again I made it so I might be wrong :)

    You can see it in action here.

提交回复
热议问题