특정 멤버로 특정 객체를 얻을 수 있을까?

Tags:

In response to 특정 멤버로 특정 객체를 얻을 수 있을까?

당연히 루비에선 쉽게 됩니다. ㅎㅎ

class Foo
    def initialize(name)
        @name = name
    end
    
    def print_name
        puts @name
    end
end

def bar(f)
    f.print_name
end

# Now, I want to add list functionality
module List
    attr_accessor :prev, :next
end

# I can change Foo whenever!
class Foo
    include List
end

f = Foo.new("test")

# Foo responds to 'print_name' message.
bar(f)
f.next = Foo.new("test2")

# Foo responds to 'next' message also.
bar(f.next)

결과는
test
test2

C++에서 메타프로그래밍으로 해결할 수는 있겠지만 쉽진 않겠죠. (30분~1시간 생각해봐야할 듯.) 자바나 C#에서 될지는 저도 잘;