Tag dispatch versus static methods on partially specialised classes

后端 未结 4 1297
無奈伤痛
無奈伤痛 2020-12-07 08:54

Suppose I want to write a generic function void f(), which does one thing if T is a POD type and another thing if T is non-PO

4条回答
  •  忘掉有多难
    2020-12-07 09:32

    A readable alternative to [boost|std]::enable_if, tags and partial specialization for simple compile-time dispatch that I like is the following:

    [Remember that booleans have conversion to integers, that zero-length arrays are invalid and that offending templates are discarded (SFINAE). Also, char (*)[n] is a pointer to an array of n elements.]

    template  
    void foo(T, char (*)[is_pod::value] = 0)
    {
        // POD
    }
    
    template  
    void foo(T, char (*)[!is_pod::value] = 0)
    {
        // Non POD
    }
    

    It also has the advantage of not needing external classes which pollute the namespace. Now, if you want to externalize the predicate like in your question, you can do:

    template 
    void foo(T, char (*)[what] = 0)
    {
        // taken when what is true
    }
    
    template 
    void foo(T, char (*)[!what] = 0)
    {
        // taken when what is false
    }
    

    Usage:

    foo::value>(some_variable);
    

提交回复
热议问题