Passing arbitrary data to a function without void pointers
I am working with an abstract base class implementing a set of system tests. In simplified form, the class declaration is:
class Test_Class
{
Test_Class();
~Test_Class();
Run_Test(void * param_set = NULL) = 0;
}
The base class requires the implementation of the Run_Test function which allows a user to pass in an arbitrary data structure as a void pointer and cast it to the appropriate type inside the body of Run_Test in a child class, in order to allow different tests to use different data structures, eg a float in one test vs a list of ints in another.
This is cumbersome and seems like an incredibly C-like way of doing things. Is there a better way of using inheritance or other language utilities?
Note: Due to customer constraints, this program is not allowed access to the STL or the Boost libraries.
Yes. User doesn't pass in an arbitary data structure but can make an arbitrary data structure by extending your base class.
class Test_Class {
Run_Test(const Config& config);
};
client code:
class MyConfig : public Config {
//...
};
Another option is templates. You can accomplish many common tasks with either, I'm not sure which is ideal in this situation so I'll leave it to other answers or to you to research that if you go this route.
If you want a set of tests, use std::vector<std::function<void()>> tests;
and then you can simply tests.push_back([=] { do_test(the_args, I_captured, from_local, scope); });
.
You can do similar tricks with std::bind
if your compiler doesn't support lambdas.
There's no need for you, the end-user, to write your own generic function interface. It already has been done.
Edit: Yes, you're going to end up with some C-style garbage if you do not A) re-implement the wheels provided by Boost or the STL or B) use the existing wheels provided by Boost or STL. There is no magical third choice between "Write own good code" or "Use other people's good code" which still results in good code.
我不记得是否有可能/如何在类内部对函数进行参数检测,所以也许会这样做:
class Test_Class {
public:
template <typename T>
void Run_Test(T p) {
}
};
template <class T>
void tester(Test_Class t, T p) {
t.Run_Test<T>(p);
}
int main() {
Test_Class p;
int a = 5;
tester(p, a);
}
链接地址: http://www.djcxy.com/p/43840.html
上一篇: 将不同的对象存储为void *并将其转换为void *
下一篇: 将任意数据传递给没有void指针的函数