How can I prevent implicit conversions in a function template?

前端 未结 1 1232
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 06:18

How can I define a function template to prevent implicit conversions?

It seems I can prevent implicit conversions using non-template functions but not using function

1条回答
  •  时光说笑
    2021-01-20 06:35

    The following overload will prevent implicit conversions:

    template 
    void no_conversions(T) = delete; // 7
    
    void no_conversions(const B&) {} // 8
    

    and leads to:

    // Requested behaviour.
    no_conversions(a); // resolves to 7
    no_conversions(b); // resolves to 8
    

    A value-overload poisons the overload set for implicit conversions as it will be an exact match.

    Edit:

    template 
    void no_conversions(const T&) = delete; // 9
    
    void no_conversions(const B&) {}        // 10
    

    works just as well.

    0 讨论(0)
提交回复
热议问题