c++ - 将 std::list<boost::any> 作为参数传递给函数

标签 c++ boost std

我正在尝试将 boost::any 对象列表传递给函数。

这是我的尝试:

typedef std::list<boost::any> Any_List_Type;
typedef std::list<int> Int_List_Type;

void printAnyListSize(Any_List_Type anyListType)
{
   printf("Any list size(%d) \n", anyListType.size();
   return;
}

void showInstListSize(Int_List_Type intListType)
{
   printAnyListSize(intListType);  //compile error...
}

由于 boost::any 允许在列表中传递任何类型,所以我不确定为什么会出错。

如何将 boost::any 类型转换为列表中的适当类型?

最佳答案

错误是因为std::list<int>不可转换为 std::list<boost::any> (或 std::list<T> 与任何其他 T ,例如 unsigned )。

可以手动转换

 printAnyListSize(Any_List_Type(intListType.begin(), intListType.end()));

您要的是协变列表类型。协变类型(类型构造函数)存在于某些语言中,例如 Scala;如果 CovT<X>X 中是协变的和 TU 的子类型(例如 int 将是 any 的子类型),然后 Cov<T>Cov<U> 的子类型.这意味着在 Scala 中,与您的示例类似的示例会起作用。

在 C++ 中,没有对协变类型的语言支持。某些类型(如 shared_ptr )通过用户定义的转换(例如转换构造函数)模拟协方差。然而,std::list不在其中。这就是您必须自己执行转换的原因。

关于c++ - 将 std::list<boost::any> 作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12639569/

相关文章:

C++ 模板,模棱两可的重载

c++ - 使用 Boost.GIL 将图像转换为 "raw"字节

c++ - 删除循环列表时找到的列表中的对象的正确方法是什么?

c++ - std::map\std::set 包含重复键

c++ - Android NDK C++ 代码的内存调试工具

c# - 使用 C# 创建 .cat 文件

c++ - 我的第一个 CPP 程序的问题 - 标题和源代码

python - boost python - 提取ndarray时nullptr

c++ - 将 boost 静态链接到 Linux 上的共享对象时遇到问题

c++ - 从 std::tuple 成员中移除引用