|
Re: Backyard Hotrodding C++
|
Posted: May 25, 2006 3:04 AM
|
|
Walter Bright is a bright fellow who wrote the D programming language. Although I like D, it is not widely adopted, and it seems to me it will never be. It seems the embedded/realtime world is satisfied with C++ while the business world is satisfied with Java.
Anyway here is another trick that one can do to hide the implementation details of a class. It requires a little bit more work, but it is more efficient than the one presented in the article.
Here is the interface of the class:
#ifndef FOO_HPP #define FOO_HPP
class foo { public: //the default constructor foo();
//the copy constructor foo(const foo &f);
//the destructor virtual ~foo();
//the assignment operator foo &operator = (const foo &f);
//get content int value() const;
//set content void set_value(int v);
private: unsigned char content[4]; };
#endif //FOO_HPP
Here is the implementation file foo.cpp:
#include "foo.hpp" #include <stdexcept> #include <iostream>
//macros for making the conversion easier #define self ((_foo *)this) #define rhs ((_foo *)&f)
//the implementation; it must have the same layout as the interface struct _foo { int value; virtual ~_foo() { } };
//the default constructor foo::foo() { self->value = 0; }
//the copy constructor foo::foo(const foo &f) { self->value = rhs->value; }
//the destructor foo::~foo() { std::cout << self->value << std::endl; }
//the assignment operator foo &foo::operator = (const foo &f) { self->value = rhs->value; return *this; }
//a method that returns data int foo::value() const { return self->value; }
//a method that sets data void foo::set_value(int v) { self->value = v; }
//a class that ensures size of interface == size of implementation template <class A, class B> struct assert_size { assert_size() { if (sizeof(A) != sizeof(B)) throw std::logic_error("implementation size different from interface size"); } };
//ensure size of interface == size of implementation static assert_size<foo, _foo> assert_size_of_foo;
and here is usage of the class:
#include "foo.hpp" #include <iostream> using namespace std;
void test() { foo f; f.set_value(10); cout << f.value() << endl; f.set_value(20); }
int main() { test(); getchar(); return 0; }
The result is:
10 20
|
|