c++ - 是否可以在 std::any 中存储引用?

标签 c++ c++17 std stdany

我正在尝试一些事情并遇到以下问题:是否有可能将对值的引用存储在 std::any 中?

我尝试了以下方法:

#include <any>
#include <iostream>
#include <functional>

auto func_by_pointer(std::any obj)
{
    *std::any_cast<int *>(obj) += 2;
}
auto modify_by_pointer(int &a)
{
    func_by_pointer(std::make_any<int *>(&a));
}

auto func_by_reference_wrapper(std::any obj)
{
    std::any_cast<std::reference_wrapper<int>>(obj).get() -= 2;
}
auto modify_by_reference_wrapper(int &a)
{
    func_by_reference_wrapper(std::make_any<std::reference_wrapper<int>>(a));
}

auto func_by_reference(std::any obj)
{
    std::any_cast<int &>(obj) *= 2;
}
auto modify_by_reference(int &a)
{
    func_by_reference(std::make_any<int &>(a));
}

int main()
{
    auto value = 3;
    std::cout << value << '\n';
    modify_by_pointer(value);
    std::cout << value << '\n';
    modify_by_reference_wrapper(value);
    std::cout << value << '\n';
    modify_by_reference(value);
    std::cout << value << '\n';
}

结果是下面的输出:

3
5
3
3

然而,我期待它是:

3
5
3
6

因此,将指针传递给 value 工作正常。将 std::reference_wrapper 传递给 value 也可以正常工作,但以某种方式传递 int& 则不起作用。我是不是在我的代码中做错了什么,或者通常不可能在 std::any 中存储引用?

最佳答案

您不能在 std::any 中存储引用因为,对于给定的类型 T , 构造函数 std::any(T)存储 std::decay_t<T> 类型的值,它删除了引用限定符:

[any.cons]

template<class T>
  any(T&& value);
  1. Let VT be decay_­t<T>.

  2. Requires: VT shall satisfy the Cpp17CopyConstructible requirements.

  3. Effects: Constructs an object of type any that contains an object of type VT direct-initialized with std::forward<T>(value).

关于c++ - 是否可以在 std::any 中存储引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56613109/

相关文章:

c++ - 具有相同类型的可变模板参数的构造函数无法编译

c++ - 如果我必须重写非虚拟成员函数怎么办

c++ - 为什么 std::rel_ops 需要相等运算符?

c++ - 尝试使用 LoadLibrary 加载 DLL 并获取 R6034 "An application has made an attempt to load the C runtime library incorrectly"

c++ - 如何找到机器上为 C 或 CPP 安装/可用的库?

c++ - 将具有不同类型的 vector 作为初始化列表传递给函数

java - 使用 jni 时在 std::_List_const_iterator<Exiv2::Exifdatum>::operator++ 中获取 SIGSEGV

c++ - std::find 条件语句未按预期工作

c++ - 如何将 C++ 引用传递给 C 函数的指针参数?

c++ - 在 C++ 中正确使用 map 迭代器