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

后端 未结 7 1877
孤城傲影
孤城傲影 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 17:49

    Well, I was going to answer this with the code below, but even though it works with Visual C++, in the sense of producing the desired compilation error, MinGW g++ 4.7.1 accepts it, and invokes the rvalue reference constructor!

    I think it must be a compiler bug, but I could be wrong, so – anyone?

    Anyway, here's the code, which may turn out to be a standard-compliant solution (or, it may turn out that that's a thinko on my part!):

    #include 
    #include       // std::is_same, std::enable_if
    using namespace std;
    
    template< class Type >
    struct Boxed
    {
        Type value;
    
        template< class Arg >
        Boxed(
            Arg const& v,
            typename enable_if< is_same< Type, Arg >::value, Arg >::type* = 0
            )
            : value( v )
        {
            wcout << "Generic!" << endl;
        }
    
        Boxed( Type&& v ): value( move( v ) )
        {
            wcout << "Rvalue!" << endl;
        }
    };
    
    void function( Boxed< int > v ) {}
    
    int main()
    {
        int i = 5;
        function( i );  //<- this is acceptable
    
        char c = 'a';
        function( c );  //<- I would NOT like this to compile
    }
    

提交回复
热议问题