c++ - 模板函数和 boost::remove_reference

标签 c++ boost

我正在追踪一个我无法弄清楚的 C++ 编译器错误。我已将其简化为以下代码:

#include <boost/config.hpp>
#include <boost/type_traits/remove_reference.hpp>

template<typename T> inline const T bar( T in )
{
    typedef BOOST_DEDUCED_TYPENAME boost::remove_reference<T>::type nonref;
    const nonref* inPtr = &in;
    return *inPtr;
}

class Foo
{
};

int main()
{
    Foo foo;
    const Foo& ref = bar< Foo& >( foo );
}

结果是:

tt.cpp: In function ‘const T bar(T) [with T = Foo&]’:
tt.cpp:19:39:   instantiated from here
tt.cpp:9:13: error: invalid initialization of reference of type ‘Foo&’ from expression of type ‘const nonref {aka const Foo}’

这里的实际问题是什么?为什么返回值中缺少const?我需要 remove_reference,因为实际代码需要它。

最佳答案

const 应用于引用类型没有任何作用。您需要使模板参数成为 const foo &,或者删除引用,然后在函数签名中添加 const 引用本身。

另见 When should I use remove_reference and add_reference?特别是第二段。

关于c++ - 模板函数和 boost::remove_reference,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10703480/

相关文章:

c++ - boost::shared_ptr 代码中的多线程错误

C++函数转换题

c++ - boost shared_lock。阅读首选?

c++ - 使用非 DefaultConstructible 谓词 boost filter_iterator

c++ - STL并行累加函数错了吗?

c++ - 命名空间 + 函数与类上的静态方法

c++ - gmtime算法的最小实现?

c++ - 初始化列表 vector 构造函数

C++ OutputIterator 后递增要求

c++ - 这些存储指针数组的方法有区别吗?