Can you use keyword explicit to prevent automatic conversion of method parameters?

后端 未结 8 1524
心在旅途
心在旅途 2020-12-04 17:18

I know you can use C++ keyword \'explicit\' for constructors of classes to prevent an automatic conversion of type. Can you use this same command to prevent the conversion

8条回答
  •  盖世英雄少女心
    2020-12-04 18:06

    Something that might work for you is to use templates. The following shows the template function foo<>() being specialized for bool, unsigned int, and int. The main() function shows how the calls get resolved. Note that the calls that use a constant int that don't specify a type suffix will resolve to foo(), so you'll get an error calling foo( 1) if you don't specialize on int. If this is the case, callers using a literal integer constant will have to use the "U" suffix to get the call to resolve (this might be the behavior you want).

    Otherwise you'll have to specialize on int and use the "U" suffix or cast it to an unsigned int before passing it on to the unsigned int version (or maybe do an assert that the value isn't negative, if that's what you want).

    #include 
    
    template 
    void foo( T);
    
    template <>
    void foo( bool x)
    {
        printf( "foo( bool)\n");
    }
    
    
    template <>
    void foo( unsigned int x)
    {
        printf( "foo( unsigned int)\n");
    }
    
    
    template <>
    void foo( int x)
    {
        printf( "foo( int)\n");
    }
    
    
    
    int main () 
    {
        foo( true);
        foo( false);
        foo( static_cast( 0));
        foo( 0U);
        foo( 1U);
        foo( 2U);
        foo( 0);
        foo( 1);
        foo( 2);
    }
    

提交回复
热议问题