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

后端 未结 7 1864
孤城傲影
孤城傲影 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:07

    You can't directly, because a char automatically gets promoted to int.

    You can resort to a trick though: create a function that takes a char as parameter and don't implement it. It will compile, but you'll get a linker error:

    void function(int i) 
    {
    }
    void function(char i);
    //or, in C++11
    void function(char i) = delete;
    

    Calling the function with a char parameter will break the build.

    See http://ideone.com/2SRdM

    Terminology: non-construcing functions? Do you mean a function that is not a constructor?

提交回复
热议问题