FAQ Database Discussion Community


Populating a julia dictionary with an array of symbols

scope,metaprogramming,julia-lang
I'm getting stuck on some basics of scope in Julia expressions. Can someone help tell me what is going wrong inside the for loop below? Inside the lopp the first expression works and the second does not, though both work with variables from the global scope. x = 1 glob_obj...

How to set a new property and provide its setter in Groovy

groovy,closures,metaprogramming
I have this groovy class: class Car { int speed = 0 } I want to use metaprogramming to introduce a new property "color" and also provide setColor method to an instance of the Car object, like this: def c = new Car() c.metaClass.setProperty("color", "red") c.metaClass.setColor = { def newColor->...

Function from `mappend` function to `Monoid` instance?

haskell,types,metaprogramming
I have a data structure (it's a specific subclass of rose-tree that forms a lattice with greatest-lower bound and lowest-upper bound functions), and it supports two perfectly reasonable functions to serve as the Monoid class's mappend. Is there any way to support anonymous Monoid instances in haskell? Is this an...

Variadic templates type deduction

c++,templates,c++11,metaprogramming
I came across this great article: http://pdimov.com/cpp2/simple_cxx11_metaprogramming.html In the following code : template<class A, template<class...> class B> struct mp_rename_impl; template<template<class...> class C, class... T, template<class...> class B> struct mp_rename_impl<C<T...>, B> { using type = B<T...>; }; template<class A, template<class...> class B> using mp_rename = typename mp_rename_impl<A, B>::type; //... mp_rename<mp_list<int, float,...

template metaprogramming to disable functionality of a class

c++,metaprogramming
I have a bunch of loosely coupled classes (with no common interface), and in my application, I have processing using these classes. I'd like to be able to come up with a generic way to disable some of these classes, so that they don't get compiled or consume runtime resource....

How in C++ use templates to call specific members of supplied type

c++,templates,c++11,metaprogramming
Lets assume we have two classes struct A { int x = 1; }; struct B { int y = 2; }; I want to have template that will return value of member (in a case of A I want to return value of "x", in case of B I...

Defining specific attr_accessor methods in order to distinguish several types of instance variables

ruby,metaprogramming
When describing classes, I would like to be able to diffentiate different kind of instance variables, using a dedicated class methods (let's call it my_attrs_1, my_attrs_2). Something like : class DesignUnit attrs_1 :a,:b attrs_2 :c end So that I can iterate through these different instance variables like this : du=DesignUnit.new...

How do I change the context of lambda?

ruby,lambda,metaprogramming
If you run the code below you get an error. class C def self.filter_clause param_1 puts param_1 yield # context of this param is class B end def hi "hello" end end class B def self.filter(value, lambda) code = lambda { filter_clause(value, &lambda) } C.instance_exec(&code) end filter(:name, ->{ hi })...

Method forwarding with composition instead of inheritance (using C++ traits)

c++,templates,inheritance,metaprogramming,composition
I would like to use composition and to write good forwarding methods for every possible overload (noexcept, const, volatile) using C++ capabilities. The idea is to use traits in order to determine whether a method is declared {noexcept / const / volatile / etc.} and to behave accordingly. Here is...

Giving object's send-method an other method with block

ruby-on-rails,ruby,metaprogramming
This one works: Beer.all.send(:sort) and also it works with block: Beer.all.sort_by{|b| b.name} Beer.all.sort_by(&:name) But when I give a executable block to send-method like this: Beer.all.send(:sort_by{|b| b.name}) Beer.all.send(:sort_by(&:name)) I get syntax error. Is there any alternative way in Ruby to give an executable block to send-method?...

Compiler says dynamic property is missing but I can see it

c#,.net,dynamic,reflection,metaprogramming
I'm starting to dive into the world of C# Dynamics and Metaprogramming, and having some trouble. I managed to create a CodeDom tree, and generate the following code: namespace Mimsy { using System; using System.Text; using System.Collections; internal class JubJub { private int _wabeCount; private ArrayList _updates; public JubJub(int wabeCount)...

Binding method to instance

ruby,metaprogramming
Is there a way to bind an existing method to an existing instance of an object if both the method and the instance are passed as symbols into a method that does that if the instance is not a symbol? For example: def some_method #do something end some_instance = Klass.new(something)...

Folding over arbitrarily many variadic packs

c++,c++11,metaprogramming,variadic-templates
I'm reading through Eric Niebler's post on his tiny metaprogramming library. In trying to implement the pieces that he omits / lists as challenges, I am left with the following implementation of transform: template <typename F, typename... As> using meta_apply = typename F::template apply<As...>; template <typename... > struct typelist_transform; //...

Boost Fusion: Nesting flatten_view and zip_view

c++,boost,metaprogramming,boost-fusion
Hi! I'm desperately trying to nest different views using Boost Fusion. I'm still in the process of learning Fusion, so apologies if this is a silly question. My actual scenario is much more complex, but I'll try to simplify it as much as possible for the sake of illustration. I...

Using local variables in define_method

ruby,metaprogramming
I would like to understand how define_method works and how to properly use the variables outside of the definition block. Here is my code: class Test def self.plugin for i in 1..2 define_method("test#{i}".to_sym) do p i end end end plugin end ob = Test.new ob.test1 #=> 2 (I would expect...

Domain class variables

grails,groovy,metaprogramming
How do domain classes in Grails have variables like static constraints ={ }? I can't see any direct inheritance. I guess it's meta-programming but can you explain this?...

Ruby - Share local variable with the obj's eigenclass

ruby,metaprogramming,eigenclass
I am trying to dynamically define methods on an initialized Ruby object MyObject based on a hash my_hash I pass to its initialize method. In the body of the initialize method, I have the following: my_hash.each do |key| class << self define_method(key.underscore.to_sym) do my_hash[key] end end end This fails with...

Go reflect. How to check whether reflect.Type is an error type?

reflection,go,metaprogramming
I need to assuredly check whether a reflect.Type is an error. There is no reflect kind for error. What is the formal/idiomatic manner to check for type error in go reflect? Go Playground Full Example //return map of default values, based on each return type of a function // error...

Singleton method chaining in ruby

ruby,metaprogramming
Is there a way to dinamically define and chain singleton methods in Ruby? Say I have a class A with a method defined and an array constant. Something like this: class A ARR = [:a, :b, :c, :d] class << self def test end end end Is there a way...

How would I implement my own Rails-style validates() method in Ruby?

ruby-on-rails,ruby,metaprogramming,mixins
I'm trying to understand some Ruby metaprogramming concepts. I think I understand classes, objects, and metaclasses. Unfortunately, I'm very unclear on exactly what happens with included Modules with respect to their instance/'class' variables. Here's a contrived question whose solution will answer my questions: Suppose I'm writing my own crappy Rails...

How can I expand call to variadic template base classes?

c++,c++11,metaprogramming,variadic-templates
I have a set of non-orthogonal policies, all of them implementing a common named method, the policies add safety checks. I want users to be able to combine the policies to allow more complex validation without creating policies for each combination case by hand. My approach is creating a new...

Can a walker be stopped?

c#,metaprogramming,antlr4
I have a ParseTree listener implementation that I'm using to fetch global-scope declarations in standard VBA modules: public class DeclarationSectionListener : DeclarationListener { private bool _insideProcedure; public override void EnterVariableStmt(VisualBasic6Parser.VariableStmtContext context) { var visibility = context.visibility(); if (!_insideProcedure && visibility == null || visibility.GetText() == Tokens.Public || visibility.GetText() == Tokens.Global)...

Defining an operator for the let statement (binding)

f#,metaprogramming
In F#, is it possible to define an operator, say (<<), that would assign a value to a variable like so : let (<<) var value = ??<let var = value>?? that would compile inside the program and for which the resulting variable var of the let assignment could be...

What is the purpose of a struct template without definition?

c++,templates,metaprogramming,boost-python
Below is a snippet from Boost.Python's source code: template <class T> struct null_ok; // how's it working? template <class T> inline null_ok<T>* allow_null(T* p) { return (null_ok<T>*)p; } It's wired that there's no definition for forward declared struct null_ok, and null_ok has nothing to do with the template argument T....

What is going on with Args…, Args&…, Args&&

c++,metaprogramming
I have this code. To get it to work I had to use Args&&... instead of Args... or Args&... I notice the args convert from & to const& or && to &. What exactly is going on with Args... Args&... and Args&&... !? When the signature was Args.. template<class V,...

Enable a function template in C++ whenever an expression is undefined

c++,templates,c++11,metaprogramming,sfinae
Can a function template be enabled whenever some expression is undefined (e.g., xof type t is not streamable to std::cout). Something like template<typename t> auto f(const t &x) -> typename enable_if_undefined<decltype(std::cout << x)>::type; Using SFINAE, I only see how to enable if the expression is defined, but not how to...

Type function that returns a tuple of chosen types

c++,templates,c++11,metaprogramming
I've implemented a type function Tuple that turn a list of My_enum values into an std::tuple of corresponding types: #include <tuple> enum My_enum{ t_int, t_double }; // Bind_type is a type function that given a My_enum returns the corresponding type template<My_enum E> struct Bind_type; template<> struct Bind_type<t_int>{ using type =...

C++ template meta-programming member function loop unrolling

c++,templates,metaprogramming,member
I have just started to use template meta-programming in my code. I have a class which has as a member which is a vector of a multi-dimensional Cartesian points. Here is a basic setup of the class: template<size_t N> class TGrid{ public: void round_points_3(){ for(std::size_t i = 0; i <...

Can function application be overriden with Macro in Elixir?

metaprogramming,elixir
Let's say I'd want to override each function call with a macro that counts how many times I called each particular function. Is it possible in Elixir? I know there is a possibility of overriding builtin macros and functions with import Kernel, except: [name: arity] import MyOwnKernel But it doesn't...

Inject outer scope when monkey-patching instance method in Ruby [duplicate]

ruby,closures,metaprogramming
This question already has an answer here: Is it possible to define a Ruby singleton method using a block? 2 answers I have a container class Foo with a method frob, and I want to add a similarly named method, which will delegate to the container, to each of...

Produce a symbol from a symbol in a macro

metaprogramming,julia-lang,julia-macros
I'm not sure how to express this. I have a macro like so: macro dothing(xxxx) # create a new symbol ZC_xxxx = symbol("ZC_"*string(xxxx)) # esc so that variables are assigned in calling scope return esc(quote # assign something to the new symbol $ZC_xxxx = [555.0, 666.0, 777.0] # Store in...

Rails, rspec: using “send()” to dynamically generate capybara URLs for controller specs

ruby,ruby-on-rails-4,metaprogramming,rspec3
Inside a controller spec for a #show action: resource_name = "adoption_transfer_type" it "returns a single resource" do resource = create(resource_name.to_sym) # Works xhr :get, api_v1_lookups_adoption_transfer_type_path(resource.id) # Does not work xhr :get, send("api_v1_lookups_#{resource_name}_path(#{resource.id})") end It results in the following error: Failure/Error: xhr :get, send("api_v1_lookups_adoption_transfer_type_path(#{resource.id})") NoMethodError: undefined method `api_v1_lookups_adoption_transfer_type_path(66)' It looks like...

How to use macros for concise, type-safe, unboxed enum?

scala,enums,metaprogramming,value-type,scala-macros
I am learning Scala macros and thinking of this as an exercise. Is it possible to use Scala macros to write down something like this (maybe not exactly this concrete syntax, but something without boilerplate) enum DayOfWeek = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday |...

Why is a delegated method public when declared in a private section?

ruby-on-rails,ruby,delegates,metaprogramming
I can make attr_reader (and the related attr_writer and attr_accessor) method(s) private by putting the declaration in a private section: class Foo private attr_reader :b end Foo.new.b # => NoMethodError: private method `b' called for #<Foo:> However, Rails' delegate and the Ruby standard library's def_delegate do not work this way....

Insert/remove type into variadic template list (parameter pack)

c++,templates,metaprogramming,variadic-templates,c++14
What is the best way of implementing index-based insertion and deletion of a type in a variadic template type list (parameter pack)? Desired code/behavior: template<typename...> struct List { /* ... */ }; static_assert(is_same < List<int, char, float>::Insert<int, 0>, List<int, int, char, float> >()); static_assert(is_same < List<int, char, float>::Insert<int, 2>, List<int,...

Meta Programming and Unit Testing in ruby

ruby-on-rails,ruby,rspec,metaprogramming
I am using rspec to do my testing and while I am not looking for full blown answer, more of a pseudo code approach to get me going - I am unsure how to write tests for the following class. module AisisWriter class ClassFactory class << self undef_method :new attr_accessor...

Ruby Yield to Subclass Method from Superclass Method

ruby,inheritance,metaprogramming
In Ruby, is it possible to yield to a subclass method from a superclass method without affecting code in the subclass? I'm trying to avoid calling super in the subclass. class SuperClass def do_something puts "getting ready..." # how to then yield back to the subclass do_something method? puts "done."...

Changing and adding arguments of method before invocation

groovy,metaprogramming
I want to reproduce the behavior of the default arguments by intercepting the call to some methods. The following code tries to give a default argument when the method display is called without arguments: class Thing { void display(String text) { println(text) } def invokeMethod(String name, args) { if(name ==...

C++ Compiler Output

c++,gcc,compiler-construction,metaprogramming,compile-time
I would like to know if there is a tool / GCC compilation switch one could use to probably see the trace / output of the GCC compiler before runtime. Generally , I would appreciate a tool annotating how the GCC compiler parsed through my code showing all precomputed static...

Specs not running as “sandbox” creating dynamic Classes

ruby,rspec,metaprogramming,ruby-2.0
I have a module with a define method that creates a class dynamically like this: require "active_support/all" class SomeBaseClass # code end module MyModule def self.define(_class_name) class_name = _class_name.classify Object.const_set(class_name, Class.new(SomeBaseClass)) end end Then, if I do: MyModule.define(:my_class) I will get: MyClass My spec: describe "#define" do it "creates a...

std::is_assignable and const pointer object

c++,templates,c++11,metaprogramming
I have a small problem when trying to deduce things with std::is_assignable My code: #include <string> #include <type_traits> class Object{}; enum my_conv { string, const_object, object }; template<typename T, typename V = void> struct deducer; template<typename T> struct deducer<T, typename std::enable_if< std::is_constructible<std::string, T>::value >::type > { static const my_conv value...

Force Preprocessor Evaluation While Tokenizing

c++,boost,metaprogramming
Is there a way to force the preprocessor to completely evaluate the symbols before tokenizing? An example of the input and output I want GFR_SER_##token, GFR_SER_INT. As an example, I'm trying to do some pre-processor meta-programming using Boost::PP. For pasting strings, it's fairly easy as you just add a level...

Why are these methods not dynamically defined at runtime by define_method?

ruby-on-rails,ruby,metaprogramming
So I have the following class below in a Rails 4.2 app that uses define_method to dynamically define class methods at runtime. When I boot up the rails console it says that the Dynamic.kite_flying and Dynamic.tail_flying methods don't exist. Is there something I'm missing to define these methods when I...

Not able to do Class(argument) with eval in ruby

ruby,eval,metaprogramming
I have a function like this: def check_if_correct_type(type, value) # nil.test! # eval(type.classify(value)) rescue return false # true case type when "integer" !!Integer(value) rescue return false when "float" !!Float(value) rescue return false else return true end true end A sample would be check_if_correct_type("integer", "a") I tried changing the function like...

Rails lib/module with 'class Class' and custom attr_accessor

ruby-on-rails,ruby,metaprogramming
I want to make my own attr_accessor like this: class Class def attr_accessor_with_onchange_callback(*args, &block) raise 'Callback block is required' unless block args.each do |arg| attr_name = arg.to_s define_method(attr_name) do self.instance_variable_get("@#{attr_name}") end define_method("#{attr_name}=") do |argument| old_value = self.instance_variable_get("@#{attr_name}") if argument != old_value self.instance_variable_set("@#{attr_name}", argument) self.instance_exec(attr_name, argument, old_value, &block) end end end...

Define Method Based on Existing Method in Ruby

ruby,metaprogramming
I'm trying to metaprogram a way to define bang methods based on predicate methods. Right now I have the behavior I want working with method_missing: class PredicateBang def true? true end def false? false end def method_missing(method, *args, &block) if bang_match = /\A([^?]+)!\z/.match(method.to_s) predicate_method = :"#{bang_match[1]}?" if respond_to?(predicate_method) unless send(predicate_method,...

Get Method Arguments using Ruby's TracePoint

ruby,metaprogramming
I'm able to get access to a Ruby method's arguments using the TracePoint API: def foo(foo_arg) end trace = TracePoint.trace(:call, :c_call) do |tp| tp.disable case tp.method_id when :foo, :sub method = eval("method(:#{tp.method_id})", tp.binding) method.parameters.each do |p| puts "#{p.last}: #{tp.binding.local_variable_get(p.last)}" end end tp.enable end trace.enable foo(10) # => foo_arg: 10 However...

Dynamic class generation with attributes

ruby,metaprogramming
I am trying to generate a dynamic class with dynamic_name = 'Person' Object.const_set(dynamic_name, Class.new {def init(attrs); end}) I would like to generate attributes for this class. I tried to do it like this: Person.class.module_eval { attr_accessor :name} But is it possible to put this directly into the init method? I...

Generic way of lazily evaluating (short-circuiting) template conditional types

c++,templates,metaprogramming,c++14,template-meta-programming
While playing around with compile-time string (variadic lists of char) manipulation, I needed to implement a way of checking if a compile-time string contained another (smaller) compile-time string. This was my first attempt: template<int I1, int I2, typename, typename> struct Contains; template<int I1, int I2, char... Cs1, char... Cs2> struct...

Returning a type depending on the parameter

c++,templates,c++11,metaprogramming
I want to have such a function that it's return type will be decided within the function(depending on the value of the parameter), but failed implementing it. (template specialization maybe?) // half-pseudo code auto GetVar(int typeCode) { if(typeCode == 0)return int(0); else if(typeCode == 1)return double(0); else return std::string("string"); }...

Boost/C++ eval_if fails

c++,templates,metaprogramming
I've been having a very difficult time with a problem illustrated by the following program: It looks like the eval_if in line 51 isn't working correctly. That is, the metafuction get_promotion_policy is being invoked when both types are not safe types. I've been working on this for two days and...

Initialize a struct's string data member with the structs non-type variadic template arguments

c++,templates,metaprogramming
I'm trying to make a struct that receives non-type variadic template arguments. I'm trying to make it initialize a string that is a data member of this struct with these template arguments, like so: template <char... Chs> struct MyStruct { string d_text; }; int main() { cout << MyStruct<'a','b'>().d_text <<...

How to dynamically define local variables [duplicate]

ruby,metaprogramming,local-variables
This question already has an answer here: How to dynamically create a local variable? 1 answer I want to loop through an array of one word strings and turn them into instances of a class. Something like this: names_array = ["jack", "james","jim"] names_array.each { |name| name = Person.new }...

Is modifying a metaclass from an external module possible?

python,metaprogramming
Let's have an external module called fields.py with a metaclass FieldModelMetaclass which alters class FieldModel: # module fields.py class FieldModelMetaclass(type): def __new__(cls, name, bases, attrs): # code to alter class creation class FieldModel(object): __metaclass__ = FieldModelMetaclass print 'run at parse time BEFORE metaclass applies' # module consumer.py import fields def...

Programmatically Alias Method that uses $& Global Variable

ruby,global-variables,metaprogramming
I'm trying to alias a method that use's Ruby's special $& (returns last regex match). I can do this manually and it works: original = String.instance_method(:sub) String.send(:define_method, :sub) do |*args, &block| puts "called" original.bind(self).call(*args, &block) end "foo".sub(/f/) { $&.upcase } called # => "Foo" However if I try to write...

INotifyChangedProperty dynamic implementation [duplicate]

c#,.net,mvvm,metaprogramming
This question already has an answer here: Implementing INotifyPropertyChanged - does a better way exist? 25 answers In most tuts they say to write method like this: private void OnPropertyChanged(string prop) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); } } and call it such as OnPropertyChanged("PropName");. But...

Abstract class not generating with CodeDom

c#,.net,dynamic,metaprogramming,codedom
I have this class definition: CodeTypeDeclaration helloWorldClass = new CodeTypeDeclaration("HelloWorld") { Attributes = MemberAttributes.Abstract | MemberAttributes.Public }; Why does this declaration generates a non-abstract class? public class HelloWorld { } ...

Critical order of enable_if template functions

c++,c++11,metaprogramming,enable-if,template-function
Why is it important to the compiler to have the following order of definition for a visitor of a std::tuple namespace TupleVisit{ //This function SHOULD BE DEFINED SECONDLY; //IN THIS CONFIGURATION COMPILER DOES NOT //SEE THE BELOW RECURSTION TERMINATION ??? template<std::size_t Idx = 0, typename Visitor, typename... T, typename std::enable_if<...

Is it possible to have a branch of code conditionally be compiled in C++?

c++11,metaprogramming,boost-mpl
Title says it all really. Sample code which illustrates the spirit of the affaire: if( std::is_constructible<T, unsigned long>::value ) { unsigned long identity = collection.rbegin()->first + 1; std::shared_ptr<T> newObject(new T(identity)); collection.insert( identity , newObject ); return true; } else { return false; } ...

Using meta programming to select member variables

c++,metaprogramming,template-meta-programming
I am trying to create a game save system using boost serialization, and want to create an easy way for clients to select member variables for serialization. Basically I want the user to input something like this: class apple : public Actor { public: int a; bool isTasty; float unimportantData;...

Is there a way to identify a Kotlin data class from a regular Kotlin class?

reflection,metaprogramming,kotlin
Is there a way to identify a Kotlin data class from a regular Kotlin class? Like using reflection maybe?

Using Metadata/Inheritance to factor out code across multiple classes

c++,templates,inheritance,metadata,metaprogramming
I have two classes that will represent two very simple databases, and each has a "Save" function which will write what's in the class to a file. Since the code within the "Save" function is very similar, I was wondering if I could factor it out. One of my colleagues...

Added method to Ruby class throws NoMethodError in MiniTest

ruby,namespaces,metaprogramming,minitest
So why is this happening? It has to be a namespace error, I just don't understand where it is. I add a method to Fixnum like so in a file file.rb module M class Fixnum def foo return true end end end then I'll make a test like so: require...

Extending association of multiple models with common method

ruby-on-rails,ruby,metaprogramming
I want to be able to extend multiple associations from the different models with common code, for example from extending_relation_method class method. But I can't achieve self inside this method to be relation object. Any suggestions? Thanks. module ModelMixin extend ActiveSupport::Concern module ClassMethods def extending_relation_method owner = proxy_association.owner # some...

Create a “negate” wrapper for a type_traits class

c++,templates,metaprogramming,template-meta-programming,typetraits
Let's say I have a Filter metafunction that filters a list of types: template<template<typename> class TFilter, typename... Ts> using Filter = MetaList</* check TFilter<T>{}() for every type in Ts... */>; The metafunction can be used like this: Filter<std::is_pod, int, char, std::string, int> // ...returns... MetaList<int, char, int> Now, I'd like...

How to define a function for a (somewhat) partially specialized class

c++,templates,metaprogramming,template-meta-programming
I'm not sure if what I'm trying to do is possible. Here's an example: template <typename T> class Ref { void Decrement(); }; template <typename T> class Collection {}; // This will error template <> template <typename T> void Ref<Collection<T>>::Decrement() {} ...

Kotlin reflection interoperability with Java

java,reflection,metaprogramming,kotlin
What are the caveats that a developer should be aware of while writing reflective code that works both with Java and Kotlin? For example, I have an existing library that uses reflection and it works well with Java. However, when I use the same with Kotlin, my reflective code doesn't...

How to compare a template template with a template instance?

c++,templates,c++11,metaprogramming,c++14
First, let me introduce you a partial solution: template <template <class...> class, typename ...> struct is_tbase_of: std::false_type { }; template <template <class...> class Type, typename ...Args> struct is_tbase_of<Type, Type<Args...>>: std::true_type { }; In common cases, it works: is_tbase_of<std::vector, std::is_integral<int>>::value; // false is_tbase_of<std::vector, std::vector<int>>::value; // true But, it does not work...

How can one print the name of an identifier or binding in Haskell?

haskell,metaprogramming,code-inspection
Supose I want to print the name and the value of a "variable" in Haskell. The name is known at compile time! Is there a better way than in the following example? module V (e, c, eV, h, hbar, nm, k, viewAllConstants) where import Text.Printf c = 2.99792458e8::Double e =...