Is it possible to take a parameter by const reference, while banning conversions so that temporaries aren't passed instead?

后端 未结 6 1506
面向向阳花
面向向阳花 2021-01-18 21:58

Sometimes we like to take a large parameter by reference, and also to make the reference const if possible to advertize that it is an input parameter. But by making the refe

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-18 22:27

    Well, if your "large parameter" is a class, the first thing to do is ensure that you mark any single parameter constructors explicit (apart from the copy constructor):

    class BigType
    {
    public:
        explicit BigType(int);
    };
    

    This applies to constructors which have default parameters which could potentially be called with a single argument, also.

    Then it won't be automatically converted to since there are no implicit constructors for the compiler to use to do the conversion. You probably don't have any global conversion operators which make that type, but if you do, then

    If that doesn't work for you, you could use some template magic, like:

    template 
    void func(const T &); // causes an undefined reference at link time.
    
    template <>
    void func(const BigType &v)
    {
        // use v.
    }
    

提交回复
热议问题