参数类型的内部构造函数 [英] Inner constructor of parametric type

查看:57
本文介绍了参数类型的内部构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对参数类型的内部构造函数中的类型注释有些困惑.

I am a bit confused about the type annotations in inner constructor of parametric type.

在JIT推理效率和运行时效率方面,以下4种方法是否有区别?

Are there any difference in the following 4 approaches, in terms of JIT inference efficiency, and runtime efficiency?

immutable MyType{T}
    x::T
    MyType{T}(x::T) = new{T}(x + x)
end

immutable MyType{T}
    x::T
    MyType(x::T) = new{T}(x + x)
end

immutable MyType{T}
    x::T
    MyType(x::T) = new(x + x)
end

immutable MyType{T}
    x::T
    MyType{T}(x::T) = new(x + x)
end

它们都为x = MyType{Int}(1)

推荐答案

根据Jeff的回答

问题1:如果类型的名称是X,并且构造函数具有 形式函数X {...}(...)然后右花括号的内容 X传递给new之后.

Question 1: If the name of the type is X, and the constructor has the form function X{...}(...) then the contents of the curly braces right after the X are passed to new.

问题2:要创建实例,类型参数必须具有确定性 值,因此new(...)始终等同于某些new {...}(...).他们 会降低到完全相同的程度.

Question 2: To make an instance, type parameters must have definite values, so new(...) is always equivalent to some new{...}(...). They will lower to the exact same thing.

他们是完全一样的东西.您的最后一个示例是规范模式:

they're exact the same thing. Your last example is a canonical pattern:

struct MyType{T}
    x::T
    MyType{T}(x::T) = new(x + x)
end

这篇关于参数类型的内部构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆