Pattern Matching and Language Variants: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0095r1.html
CppCon 2016: David Sankel 「Variants: Past, Present, and Future": https://www.youtube.com/watch?v=k3O4EKX4z1c
// This lvariant implements a value representing the various commands
// available in a hypothetical shooter game.
lvariant command {
std::size_t set_score; // Set the score to the specified value
std::monostate fire_missile; // Fire a missile
unsigned fire_laser; // Fire a laser with the specified intensity
double rotate; // Rotate the ship by the specified degrees.
};
// Output a human readable string corresponding to the specified "cmd" command
// to the specified "stream".
std::ostream operator&<&<( std::ostream stream, const command cmd ) {
return inspect( cmd ) {
set_score value =&>
stream &<&< "Set the score to " &<&< value &<&< ".
"
fire_missile m =&>
stream &<&< "Fire a missile.
"
fire_laser intensity:
stream &<&< "Fire a laser with " &<&< intensity &<&< " intensity.
"
rotate degrees =&>
stream &<&< "Rotate by " &<&< degrees &<&< " degrees.
"
};
}
// Create a new command "cmd" that sets the score to "10".
command cmd = command::set_score( 10 );
boost::any a = "x";
auto r = switch_(a)(
case_&([](auto) -&> int { return 1; }),
case_&([](auto) -&> long { return 2l; }),
default_([]() -&> long long { return 3ll; })
);
// r is inferred to be a long long
static_assert(std::is_same&{}, "");
assert(r == 2ll);
實現在這裡
還有@霧雨魔理沙 用C++造出的幾(dai)何(shu)數據類型,帶模式匹配,用起來是這樣的
typedef algebraic_data_type&< size_t, recursive_indicator, std::tuple&< recursive_indicator, recursive_indicator &> &> exp;
DECLARE_CONSTRUCTOR( exp, 0, var, T );
DECLARE_CONSTRUCTOR( exp, 1, abs, T );
DECLARE_CONSTRUCTOR( exp, 2, app, T );
exp update_index( const exp self, size_t i, size_t current_depth )
{
return
self.match(
with( var( arg ), []( size_t ii ) { return var( ii &> current_depth ? ii + i - 1 : ii ); } ),
with(
app( arg, arg ),
[]( const exp l, const exp r )
{ return app( update_index( l, i, current_depth ), update_index( r, i, current_depth ) ); } ),
with(
abs( arg ),
[]( const exp ex ) { return abs( update_index( ex, i, current_depth + 1 ) ); } ) );
}
實現在這裡
MarisaKirisame/algebraic_data_type
這可是C++,沒有什麼是模板黑魔法解決不了的,如果有,就再糊一層宏
感覺如果在 C++ 里匹配的就不是 表面上的整個模式 而是分開的部分(全部)欄位了…類似於 scala編譯成位元組碼之後的