Equivalent of C++ static member?

449 views
Skip to first unread message

Tim Keitt

unread,
Sep 21, 2013, 4:29:29 PM9/21/13
to julia...@googlegroups.com
I want to create a lot of instances of a composite type, but give each a globally unique id. In C++ I would use a static member for access within constructors. Any thoughts on how to accomplish that?

THK

Tim Holy

unread,
Sep 21, 2013, 5:06:09 PM9/21/13
to julia...@googlegroups.com
One way might be to use an inner constructor:

module MyModule

type MyObject
data::ASCIIString
id::Int

ID::Int = 0
function MyObject(str::ASCIIString)
ID += 1
new(str, ID)
end
end

end



julia> o1 = MyModule.MyObject("Hi")
MyObject("Hi",1)

julia> o2 = MyModule.MyObject("there")
MyObject("there",2)

Tim Keitt

unread,
Sep 21, 2013, 5:26:13 PM9/21/13
to julia...@googlegroups.com
On Sat, Sep 21, 2013 at 4:06 PM, Tim Holy <tim....@gmail.com> wrote:
On Saturday, September 21, 2013 01:29:29 PM Tim Keitt wrote:
> I want to create a lot of instances of a composite type, but give each a
> globally unique id. In C++ I would use a static member for access within
> constructors. Any thoughts on how to accomplish that?

One way might be to use an inner constructor:

module MyModule

type MyObject
    data::ASCIIString
    id::Int

    ID::Int = 0
    function MyObject(str::ASCIIString)
        ID += 1
        new(str, ID)
    end
end

end


Strange. Is ID now part of the composite type or does it simply exist in the scope of the type? Eg could I do o2.ID = 10?

What makes ID different if its not part of the type? Because of the assignment in the declaration?

THK
 

julia> o1 = MyModule.MyObject("Hi")
MyObject("Hi",1)

julia> o2 = MyModule.MyObject("there")
MyObject("there",2)

Stefan Karpinski

unread,
Sep 22, 2013, 12:07:35 PM9/22/13
to Julia Users
ID is a local variable inside of the scope of the type block, not a field of the MyObject type. In particular, there's no way to manipulate it from outside (just like any other variable with local scope).

There is also a function object_id that will give you a unique Uint64 for any value that is consistent with Julia's sense of object identity – i.e. 1 === 1 but [1] !== [1] – see Baker's EGAL predicate. That might avoid having to actually assign explicit IDs.

Viral Shah

unread,
Sep 25, 2013, 1:24:13 AM9/25/13
to julia...@googlegroups.com
Are you the same Tim Keitt as here: http://www.keittlab.org ?

-viral

Tim Keitt

unread,
Sep 25, 2013, 3:13:35 PM9/25/13
to julia...@googlegroups.com
Hi Viral!

THK

Viral Shah

unread,
Sep 25, 2013, 3:22:16 PM9/25/13
to julia...@googlegroups.com
Tim - Great to see you here and trying out julia!

-viral
Reply all
Reply to author
Forward
0 new messages