How do I make the method return type generic?

You could define callFriend this way: public <T extends Animal> T callFriend(String name, Class<T> type) { return type.cast(friends.get(name)); } Then call it as such: jerry.callFriend(“spike”, Dog.class).bark(); jerry.callFriend(“quacker”, Duck.class).quack(); This code has the benefit of not generating any compiler warnings. Of course this is really just an updated version of casting from the pre-generic days and … Read more

How can I index a MATLAB array returned by a function without first assigning it to a local variable?

It actually is possible to do what you want, but you have to use the functional form of the indexing operator. When you perform an indexing operation using (), you are actually making a call to the subsref function. So, even though you can’t do this: value = magic(5)(3, 3); You can do this: value … Read more

How do I execute a command and get the output of the command within C++ using POSIX?

#include <cstdio> #include <iostream> #include <memory> #include <stdexcept> #include <string> #include <array> std::string exec(const char* cmd) { std::array<char, 128> buffer; std::string result; std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, “r”), pclose); if (!pipe) { throw std::runtime_error(“popen() failed!”); } while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) { result += buffer.data(); } return result; } Pre-C++11 version: #include <iostream> #include <stdexcept> #include … Read more