const references in c++ templates

后端 未结 3 1237
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 09:53

In a C++ template with the generic type T, I can use

const T &

to get a reference to a constant T. However, if now T itself is a reference

3条回答
  •  清歌不尽
    2021-02-05 10:10

    I have encountered the very same problem. It seems that the '&' type conversion operator binds stronger than the 'const' qualifier. So when we have this code:

    template
    void fun(const t i)
    {
    }
    
    fun();
    

    the function ends up with type void(int&), not the expected void(const int&).

    To solve this problem, I have defined this template:

    template struct constify { typedef t type; };
    template struct constify { typedef const t& type; };
    

    Now define your function as:

    template
    void fun(typename constify::type i)
    {
    }
    
    fun();
    

    The instantiated function will have the type void(const int&), as needed.

提交回复
热议问题