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

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

    Here's a general solution that causes an error at compile time if function is called with anything but an int

    template 
    struct is_int { static const bool value = false; };
    
    template <>
    struct is_int { static const bool value = true; };
    
    
    template 
    void function(T i) {
      static_assert(is_int::value, "argument is not int");
      return;
    }
    
    int main() {
      int i = 5;
      char c = 'a';
    
      function(i);
      //function(c);
    
      return 0;
    }
    

    It works by allowing any type for the argument to function but using is_int as a type-level predicate. The generic implementation of is_int has a false value but the explicit specialization for the int type has value true so that the static assert guarantees that the argument has exactly type int otherwise there is a compile error.

提交回复
热议问题