Template class methods definition with enable_if as template parameter

前端 未结 2 1447
天涯浪人
天涯浪人 2021-02-05 22:07

I asked this question earlier where a solution was presented. The solution is great as far as the question is concerned, but now I am confused on how I would define the methods

2条回答
  •  礼貌的吻别
    2021-02-05 22:21

    Here's how SFINAE can actually work with partial specialization:

    template
    struct Foo {
        /* catch-all primary template */
        /* or e.g. leave undefined if you don't need it */
    };
    
    template
    struct Foo::value>::type> {
        /* matches types derived from BasePolicy */
        Foo();
    };
    

    The definition for that constructor can then be awkwardly introduced with:

    template
    Foo::value>::type>::Foo()
    {
        /* Phew, we're there */
    }
    

    If your compiler supports template aliases (it's a C++11 feature) that then you can cut a lot of the verbosity:

    template
    using EnableIfPolicy = typename std::enable_if::value>::type;
    
    // Somewhat nicer:
    
    template
    struct Foo> {
        Foo();
    };
    
    template
    Foo>::Foo() {}
    

    Note: your original answer referred to utilies from Boost, like boost::enable_if_c and boost::is_base_of. If you're using that instead of std::enable_if and std::is_base_of (which are from C++11), then usage looks like

    typename boost::enable_if >::type
    

    which has the advantage of getting rid of one ::value.

提交回复
热议问题