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

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

    I first tried PiotrNycz's approach (for C++03, which I'm forced to use for a project), then I tried to find a more general approach and came up with this ForcedType template class.

    template 
    struct ForcedType {
        ForcedType(T v): m_v(v) {}
        operator T&() { return m_v; }
        operator const T&() const { return m_v; }
    
    private:
        template 
        ForcedType(T2);
    
        T m_v;
    };
    
    template 
    struct ForcedType {
        ForcedType(const T& v): m_v(v) {}
        operator const T&() const { return m_v; }
    
    private:
        template 
        ForcedType(const T2&);
    
        const T& m_v;
    };
    
    template 
    struct ForcedType {
        ForcedType(T& v): m_v(v) {}
        operator T&() { return m_v; }
        operator const T&() const { return m_v; }
    
    private:
        template 
        ForcedType(T2&);
    
        T& m_v;
    };
    

    If I'm not mistaken, those three specializations should cover all common use cases. I'm not sure if a specialization for rvalue-reference (on C++11 onwards) is actually needed or the by-value one suffices.

    One would use it like this, in case of a function with 3 parameters whose 3rd parameter doesn't allow implicit conversions:

    function(ParamType1 param1, ParamType2 param2, ForcedType param3);
    

提交回复
热议问题