我正在尝试将 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
中是协变的和 T
是 U
的子类型(例如 int
将是 any
的子类型),然后 Cov<T>
是 Cov<U>
的子类型.这意味着在 Scala 中,与您的示例类似的示例会起作用。
在 C++ 中,没有对协变类型的语言支持。某些类型(如 shared_ptr
)通过用户定义的转换(例如转换构造函数)模拟协方差。然而,std::list
不在其中。这就是您必须自己执行转换的原因。
关于c++ - 将 std::list<boost::any> 作为参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12639569/