gpt4 book ai didi

c++ - 使用 `(boost::any a)` 而不是 `(const boost::any& a)` 来防止引用到引用

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:55:09 26 4
gpt4 key购买 nike

First comes the definition of our new function object, contains_t. It could have inherited from the helper class std::unary_function (part of the C++ Standard Library, intended to facilitate the creation of the correct typedefs) and have the argument and result types defined automatically, but to make things clear, the required typedefs are provided explicitly. The argument type has changed from const boost::any& to boost::any, to avoid a potential reference-to-reference, which is illegal. The implementation is just as before, only here it is placed in the function call operator.

template <typename T> struct contains_t {
typedef boost::any argument_type;
typedef bool result_type;
bool operator()(boost::any a) const {
return typeid(T)==a.type();
}
};

为什么以下实现有可能接收引用对引用?

template <typename T> struct contains_t {
typedef boost::any argument_type;
typedef bool result_type;
bool operator()(const boost::any& a) const {
return typeid(T)==a.type();
}
};

谢谢

最佳答案

因为 boost::any 可以存储任何东西,所以它也可以存储引用。因此,如果您有对 boost::any 的引用,您可能会意外地以对内部引用的引用结束。

即boost::any 可以表示任何类型 T。让 T 是类型 U 的引用,即 T = U&。因此,获取类型 T 的引用会创建对类型 U 的引用,这在 C++03 中是不允许的(尽管 C++11 将允许)。

关于c++ - 使用 `(boost::any a)` 而不是 `(const boost::any& a)` 来防止引用到引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10839252/

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