Conveniently Declaring Compile-Time Strings in C++

I haven’t seen anything to match the elegance of Scott Schurr’s str_const presented at C++ Now 2012. It does require constexpr though. Here’s how you can use it, and what it can do: int main() { constexpr str_const my_string = “Hello, world!”; static_assert(my_string.size() == 13, “”); static_assert(my_string[4] == ‘o’, “”); constexpr str_const my_other_string = my_string; … Read more

Is it possible to implement dynamic getters/setters in JavaScript?

This changed as of the ES2015 (aka “ES6”) specification: JavaScript now has proxies. Proxies let you create objects that are true proxies for (facades on) other objects. Here’s a simple example that turns any property values that are strings to all caps on retrieval, and returns “missing” instead of undefined for a property that doesn’t … Read more

How to call methods dynamically based on their name? [duplicate]

What you want to do is called dynamic dispatch. It’s very easy in Ruby, just use public_send: method_name=”foobar” obj.public_send(method_name) if obj.respond_to? method_name If the method is private/protected, use send instead, but prefer public_send. This is a potential security risk if the value of method_name comes from the user. To prevent vulnerabilities, you should validate which … Read more

Overriding special methods on an instance

Python usually doesn’t call the special methods, those with name surrounded by __ on the instance, but only on the class. (Although this is an implementation detail, it’s characteristic of CPython, the standard interpreter.) So there’s no way to override __repr__() directly on an instance and make it work. Instead, you need to do something … Read more

Is it possible to figure out the parameter type and return type of a lambda?

Funny, I’ve just written a function_traits implementation based on Specializing a template on a lambda in C++0x which can give the parameter types. The trick, as described in the answer in that question, is to use the decltype of the lambda’s operator(). template <typename T> struct function_traits : public function_traits<decltype(&T::operator())> {}; // For generic types, … Read more