Skip to main content

Magic Conversions in C++

One feature that I like a lot in Rust is return type polymorphism, best exemplified with the following snippet of code:

use std::collections::HashSet;

fn main() {
    let vec: Vec<_> = (0..10).filter(|a| a % 2 == 0).collect();
    let set: HashSet<_> = (0..10).filter(|a| a % 2 == 0).collect();
    println!("vec: {:?}", vec);
    println!("set: {:?}", set); 
}

We have the same expression ((0..10).filter(|a| a % 2 == 0).collect()) that results in two totally different types of values (a Vec and a HashSet)!

This is because Rust allows you to write a function which is generic in its return type, which is a super-power that C++ does not have. But is there a way to emulate this behaviour with some clever code?