- 论坛徽章:
- 14
|
希望printf可以不需要%d,%f等来指示参数类型,因为一不小心经常会指错,而且某些类型(比如time_t,fpos_t等)还实现相关。
以下只是一个Demo,完美的最终形态应该类似于 printf( 12.3, {“%+06.1”,12.3}, 123, {HEX,123} );
以下代码在MinGW4.8.1上编译通过- #include <cstdio>
- template<typename T> void print( const T& a );
- template<typename Head, typename... Last>
- void print( Head head, Last... last )
- {
- print( head );
- printf( ", " );
- print( last... );
- }
- template<> void print<char>( const char& a )
- {
- printf( "%c", a );
- }
- template<> void print<const char*>( const char* const& a )
- {
- printf( "%s", a );
- }
- template<> void print<int>( const int& a )
- {
- printf( "%d", a );
- }
- template<> void print<double>( const double& a )
- {
- printf( "%f", a );
- }
- // [对以上代码的解释] 需要将所有内建类型都写上,这里只写了几个,意思一下而已
- struct foo
- {
- unsigned val;
- };
- template<> void print<foo>( const foo& a )
- {
- printf( "%c", 'A'+(a.val%25) );
- }
- // [对以上代码的解释] 这里可以定义 自定义类型 的输出,只是一个DEMO而已
- int main( void )
- {
- print( 'a', "Hello world", 1, 23.456, foo{0} );
- return 0;
- }
复制代码 |
|