How do I avoid implicit conversions on non-constructing functions?

后端 未结 7 1888
孤城傲影
孤城傲影 2020-11-27 17:25

How do I avoid implicit casting on non-constructing functions?
I have a function that takes an integer as a parameter,
but that function will also take characters, b

7条回答
  •  天命终不由人
    2020-11-27 18:14

    Define function template which matches all other types:

    void function(int); // this will be selected for int only
    
    template 
    void function(T) = delete; // C++11 
    

    This is because non-template functions with direct matching are always considered first. Then the function template with direct match are considered - so never function will be used. But for anything else, like char, function will be used - and this gives your compilation errrors:

    void function(int) {}
    
    template 
    void function(T) = delete; // C++11 
    
    
    int main() {
       function(1);
       function(char(1)); // line 12
    } 
    

    ERRORS:

    prog.cpp: In function 'int main()':
    prog.cpp:4:6: error: deleted function 'void function(T) [with T = char]'
    prog.cpp:12:20: error: used here
    

    This is C++03 way:

    // because this ugly code will give you compilation error for all other types
    class DeleteOverload
    {
    private:
        DeleteOverload(void*);
    };
    
    
    template 
    void function(T a, DeleteOverload = 0);
    
    void function(int a)
    {}
    

提交回复
热议问题