What is monomorphisation with context to C++?

前端 未结 4 1852
孤独总比滥情好
孤独总比滥情好 2020-11-30 23:00

Dave Herman\'s recent talk in Rust said that they borrowed this property from C++. I couldn\'t find anything around the topic. Can somebody please explain what monomorphisat

4条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 23:25

    There is a nice explanation of monomorphization in the Rust Book

    Monomorphization is the process of turning generic code into specific code by filling in the concrete types that are used when compiled.

    From the book example, if you have defined variables with Some:

    let integer = Some(5);
    let float = Some(5.0);
    

    When Rust compiles this code, it performs monomorphization. During that process, the compiler reads the values that have been used in Option instances and identifies two kinds of Option: one is i32 and the other is f64. As such, it expands the generic definition of Option into Option_i32 and Option_f64, thereby replacing the generic definition with the specific ones.

    The monomorphized version of the code looks like the following. The generic Option is replaced with the specific definitions created by the compiler:

    Filename: src/main.rs

    enum Option_i32 {
        Some(i32),
        None,
    }
    
    enum Option_f64 {
        Some(f64),
        None,
    }
    
    fn main() {
        let integer = Option_i32::Some(5);
        let float = Option_f64::Some(5.0);
    }
    

提交回复
热议问题