2013-04-05 34 views
-1

如何实现ostream-like类从零开始使用printf只?
对我来说貌似问题是在选择格式字符串,这实际上等于确定input`s型和治疗精度ostream实现使用printf

回答

1

我假定你的意思是,通过“一个ostream般的类”重载operator<<。仅通过重载就可以很容易地识别函数的参数类型。例如,您可能有:

ostreamlike& ostreamlike::operator<<(int x) 
{ 
    printf("%d", x); 
    return *this; 
} 

ostreamlike& ostreamlike::operator<<(float x) 
{ 
    printf("%f", x); 
    return *this; 
} 

输出的格式取决于选择哪个超载。

0

这取决于你想要接近真实的ostream。假设你想正确地做到这一点,你还需要一个streambuf派生类。 ostream只做格式化,实际的I/O由内部的streambuf派生类完成。由于streambuf没有格式化的I/O,因此您需要使用fwrite而不是printf

如果您的目标只是在已有的FILE*指针上进行I/O操作,那么这就是要走的路。你从streambuf派生出一个班级,说streambuf_with_FILE,然后你从ostream派生出另一个班级,说ostream_with_FILEstreambuf_with_FILE将覆盖相应的方法来执行实际的I/O并且ostream_with_FILE有一个内部的streambuf_with_FILE对象。实际上只需要很少的代码。

1

认为,这可能是类似的东西

#include <stdio.h> 

class ostreamlike { 
public: 
    ostreamlike(FILE* f_): f(f_) {} 

    ostreamlike& write(int n) { 
    fprintf(f, "%d", n); 
    return *this; 
    } 

    ostreamlike& write(const char* n) { 
    fprintf(f, "%s", n); 
    return *this; 
    } 

private: 
    FILE* f; 
}; 

// operator for types that is supported ostreamlike internally 
template <typename type> 
ostreamlike& operator<<(ostreamlike& stream, const type& data) { 
    return stream.write(data); 
} 

// external implementations to write using ostreamlike 
ostreamlike& operator<<(ostreamlike& stream, bool data) { 
    return stream.write(data ? "true" : "false"); 
} 

int main() { 
    ostreamlike s(stdout); 
    s << "hello " << 1 << " : " << true << "\n"; 
    return 0; 
}