.net - Runtime errors with User-defined conversion functions accessed via generic methods -
.net - Runtime errors with User-defined conversion functions accessed via generic methods -
i trying implement generic function wraps ancient library on c++ side. old code predates templates, , there many functions of form fooint, foodouble, fooobject etc. ideally, function phone call can done single generic function, foo. ran issues trying implement this, , have reproduced issues basic example:
ref class bar { public: system::uint32 myint = 0; bar(system::uint32 in){ myint = in; } operator system::uint32() { homecoming myint; } }; generic <typename t> t foo(system::uint32 value) { auto t = %bar(value); homecoming (t) t; } int main() { //=======works======= auto t = %bar(123); system::console::writeline((system::uint32)t); //=======doesn't work :(======= system::console::write(foo<system::uint32>(123)); homecoming 0; }
when run, code produce error an unhandled exception of type 'system.invalidcastexception'
upon reaching return (t) t;
statement in foo()
.
this code work fine templates, however, intended used in .net environments, not exposed outside of library , not solution woes. ideas?
a valid workaround create method in bar
takes in system::type^
, returns object of type, upcast object^
:
ref class bar { public: system::uint32 myint = 0; bar(system::uint32 in){ myint = in; } object^ get(system::type^ in) { if (in == system::uint32::typeid) homecoming myint; //add more types here. else homecoming nullptr; } }; generic <typename t> t foo(system::uint32 value) { auto t = %bar(value); homecoming (t)t->get(t::typeid); } int main() { system::console::write(foo<system::uint32>(123)); homecoming 0; }
note removed user-defined conversion function brevity's sake, required if wished static casting shown in question.
.net generics c++-cli
Comments
Post a Comment