gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:04:24 24 4
gpt4 key购买 nike

我正在追踪一个我无法弄清楚的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com