Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何使用对对象的引用初始化boost::any?_C++_C++11_Boost Any - Fatal编程技术网

C++ 如何使用对对象的引用初始化boost::any?

C++ 如何使用对对象的引用初始化boost::any?,c++,c++11,boost-any,C++,C++11,Boost Any,我想在boost::any对象中存储对对象的引用。如何初始化boost::any对象?我尝试了std::ref(),但是boost::any使用std::reference\u包装器进行初始化。例如,以下 #include <boost/any.hpp> #include <cxxabi.h> #include <iostream> int main(void) { int s; int i = 0; boost::any x(std::ref(

我想在
boost::any
对象中存储对对象的引用。如何初始化boost::any对象?我尝试了
std::ref()
,但是
boost::any
使用
std::reference\u包装器进行初始化。例如,以下

#include <boost/any.hpp>
#include <cxxabi.h>
#include <iostream>

int main(void)
{
  int s;
  int i = 0;
  boost::any x(std::ref(i));
  std::cout << abi::__cxa_demangle(x.type().name(), 0, 0, &s) << "\n";
  return 0;
}
#包括
#包括
#包括
内部主(空)
{
int-s;
int i=0;
boost::任意x(std::ref(i));

std::coutboost::any
类没有允许这样做的接口:您需要使用构造函数指定引用的类型。我认为您不能显式指定模板构造函数的类型,因为我看不到任何可以粘贴它的地方。即使您可以显式指定template参数,它在C++2003 B中不起作用,因为没有可用的引用折叠,并且该参数被声明为采用
t常量&
:您将尝试创建一个不会飞行的
t&const&
。 我认为最好的选择是使用
std::reference\u wrapper
,如果您坚持使用类似远程引用的东西,或者只使用
T*


也就是说,通常可以使用类似于
boost::any
类型的模板化静态因子方法来显式指定模板参数。但是,由于
boost::any
是专门设计用于处理值类型的,所以没有这样做。我有点怀疑是否应该这样做很好:使用指针是一个很好的选择。如果你真的需要一个引用类型,你可能必须自己实现它。

这个行为是正确的、预期的和适当的。
std::ref
是一个帮助函数,它创建一个类型为
std::reference\u wrapper
的对象,而引用wrapper是一个具有保存引用的值语义——如果希望容器跟踪外部引用,那么这正是您希望放入容器中的内容

所以,只需按照你的解决方案去做就行了


如果你愿意,你就不能有一个直接的、裸引用的容器,就像你不能有一个引用数组一样。包装器的设计正是为了满足这种需求。

顺便说一句,引用类型没有类型信息,而被引用类型的类型信息是
std::reference_wrapper<int>