templates - 是否可以在 Julia 中声明对任何结构的一般引用?

标签 templates struct types reference julia

我想知道是否可以在结构中实现通用引用。 代码是:

struct Foo1
  ia :: Int
end


struct Foo2{UNKNOWNTYPE}
  ref :: UNKNOWNTYPE
  ib :: Int
  
  function Foo2{UNKNOWNTYPE}(ref::UNKNOWNTYPE,ib::Int)
    o = new{UNKNOWNTYPE}(ref,ib) 
    return o
  end
end

foo1 = Foo1();
foo2 = Foo2{Foo1}(foo1,1)

在上面的代码中,struct Foo2 中的变量ref 的类型直到运行时才确定。上面的代码不起作用,它显示:“LoadError("main.jl", 6, UndefVarError(:UNKNOWNTYPE))”。

最佳答案

您基本上只是在构造函数定义中遗漏了一个where UNKNOWNTYPE。我建议像这样为 Foo2 使用外部构造函数

julia> struct Foo1
         ia::Int
       end

julia> struct Foo2{T}
         ref::T
         ib::Int
       end

julia> Foo2(ref::T, ib::Int) where T = Foo2{T}(ref, ib)
Foo2

julia> Foo2(Foo1(1), 1)
Foo2{Foo1}(Foo1(1), 1)

但是内部构造器也可以工作:

julia> struct Foo3{T}
         ref::T
         ib::Int

         function Foo3(ref::T, ib::Int) where T
           return new{T}(ref, ib)
         end
       end

julia> Foo3(Foo1(1), 2)
Foo3{Foo1}(Foo1(1), 2)

关于templates - 是否可以在 Julia 中声明对任何结构的一般引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69141687/

相关文章:

PHP MySQL SELECT 文本被截断

c++ - 模板有问题。错误 : Cannot deduce template argument for type 'T'

c++ - 编译器错过了现有的重载

apache - 让 Apache 动态修改静态网页

c++ - g++ 错误 : expected primary-expression

C - 使用指针查找最大值

c++ - 标记字符串

golang 中的 Json 解码类型模型

java - 发现不兼容的类型 : void, 出了什么问题?

c - 不同类型如何存储在内存中