GCC error with variadic templates: “Sorry, unimplemented: cannot expand ‘Identifier…’ into a fixed-length argument list”

There is a trick to get this to work with gcc. The feature isn’t fully implemented yet, but you can structure the code to avoid the unimplemented sections. Manually expanding a variadic template into a parameter list won’t work. But template specialization can do that for you. template< char head, char … rest > struct … Read more

Find out whether a C++ object is callable

I think this trait does what you want. It detects operator() with any kind of signature even if it’s overloaded and also if it’s templatized: template<typename T> struct is_callable { private: typedef char(&yes)[1]; typedef char(&no)[2]; struct Fallback { void operator()(); }; struct Derived : T, Fallback { }; template<typename U, U> struct Check; template<typename> static … Read more

Adding an instance variable to a class in Ruby

Ruby provides methods for this, instance_variable_get and instance_variable_set. (docs) You can create and assign a new instance variables like this: >> foo = Object.new => #<Object:0x2aaaaaacc400> >> foo.instance_variable_set(:@bar, “baz”) => “baz” >> foo.inspect => #<Object:0x2aaaaaacc400 @bar=\”baz\”>

define_method: How to dynamically create methods with arguments

If I understand your question correctly, you want something like this: class Product class << self [:name, :brand].each do |attribute| define_method :”find_by_#{attribute}” do |value| all.find {|prod| prod.public_send(attribute) == value } end end end end (I’m assuming that the all method returns an Enumerable.) The above is more-or-less equivalent to defining two class methods like this: … Read more

Executing code for every method call in a Ruby module

Like this: module M def self.before(*names) names.each do |name| m = instance_method(name) define_method(name) do |*args, &block| yield m.bind(self).(*args, &block) end end end end module M def hello puts “yo” end def bye puts “bum” end before(*instance_methods) { puts “start” } end class C include M end C.new.bye #=> “start” “bum” C.new.hello #=> “start” “yo”