首页 > 解决方案 > C++ CLI 通用函数

问题描述

我需要一个将 std::vector 转换为 CLI 列表的函数

        generic<typename T> where T:CliCommonObjectBase
        List<T>^ Converter::ConvertDataBaseListToList(DBList<TMObject> list)
        {           
            List<T>^ returnList = gcnew List<T>();

            for (DBIterator<TMObject> iter = list.first(); !iter.done(); iter.next())
            {
                DBRef<TMObject> tempObject = *iter;
                returnList->Add(gcnew T("BlaBla"));

            }

            return returnList;
            
        }

来自 CliCommonObjectBase 的构造函数

CliCommonObjectBase(String^ objectRefString);

通话

ConvertDataBaseListToList<CliMeeting^>(getReadBase()->getTermine());

CliMeeting 继承 CliCommonObjectBase

我的问题是 gcnew T("BlaBla") 给出错误

标签: c++-cliclr

解决方案


我做了一个小例子,如何使用其中包含参数的构造函数来实例化泛型类型:

using namespace System;

ref struct A
{
    A(String^ s)
    {
        Console::WriteLine(s);
    }
};

generic<typename T> where T : A
T CreateObject()
{
    auto args = gcnew array<Object^>(1);
    args[0] = "BlaBla";
    return static_cast<T>(Activator::CreateInstance(T::typeid, args));
}

推荐阅读