cpp日常
1.
template< typename Arg, typename ... Args >
struct overloader : Arg, overloader<Args...>
{
using Arg::operator();
using overloader<Args...>::operator();
overloader( Arg arg_, Args ... args_ )
: Arg(arg_), overloader<Args...>( args_... ) {}
};
template< typename Arg >
struct overloader<Arg> : Arg
{
overloader( Arg arg_ ) : Arg(arg_){}
};
template< typename ... Args >
auto make_overloader( Args ... args_ )
{
return overloader<Args...>{ args_... };
}
int main()
{
auto ov = make_overloader(
[](int){},
[](double){},
[](char const* const){},
[](int, int){},
[](bool, int){},
[](double, char){}
);
ov( 1 );
ov( 1.0 );
ov( "hello world" );
ov( 0, 0 );
ov( true, 100 );
ov( 3.14, 'p' );
}
2.
struct Base { void operator()(int n) const {...} };
struct Overload1:Base { void operator()(double n) const {...} };
struct Overload2:Overload1 { void operator()(std::string n) const {...} };
Overload2 func;
func(10);
func(4.2);
func("abc");
3.
如果explicit能修饰普通函数就好了。
explicit void foo(const std::string&) {}
int main()
{
foo("test"); // error
foo(std::string("test")); // error
const std::string str{"test"};
foo(str); // ok
}