-1

I need a function that's convert a std::vector to an CLI List

        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;
            
        }

the Constructor from CliCommonObjectBase

CliCommonObjectBase(String^ objectRefString);

the call

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

CliMeeting inherit CliCommonObjectBase

My Problem is the gcnew T("BlaBla") gives an error

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • 1
    You need to use auto `t = Activator::CreateInstance(typeof(T), "BlaBla");` for that. I am not 100% sure about the arguments. – RoQuOTriX Oct 01 '21 at 05:39
  • You have to check for runtime exceptions here – RoQuOTriX Oct 01 '21 at 05:55
  • There are no Runtime Exceptions –  Oct 01 '21 at 05:57
  • You sure? Because for me it doesn't work :D – RoQuOTriX Oct 01 '21 at 06:01
  • The constraint is not good enough. All that the compiler knows is that the base class has a constructor that takes a string. No guarantee that the derived class has one as well. You'll need a factory function, [example](https://stackoverflow.com/questions/700966/generic-type-in-constructor). – Hans Passant Oct 01 '21 at 12:18

1 Answers1

0

I made a small example how to instantiate a generic type with a constructor which has arguments in it:

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));
}
RoQuOTriX
  • 2,871
  • 14
  • 25