variadic template with function(args)... expansion - c++11

Today, my colleague showed me an amazing c++ expansion trick by varadic template with function calls. In succinct, it looks like:
template <typename T, T... I>
void print_sequence(std::integer_sequence<T, I...>) {
std::initializer_list<bool>{ bool(std::cout << I << ' ')... };
}
Then I find something similar from wiki/Variadic_template, and stackoverflow Unpacking a typelist e.g,
template<typename... Args> inline void pass(Args&&...) {}
template<typename... Args> inline void expand(Args&&... args) {
pass( some_function(args)... );
}
expand(42, "answer", true);
i really struggle with this style some_function(args)..., even by reading the above wiki link. How does this work? and why it has to be non-void return type? does it solely work with function or any kind of applicable expression? e.g., from another stackoverflow post Converting Variadic template pack into std::initializer_list
template<typename ...Args>
void foo () {
fun({Args::value...});
}
is the above ... binding with Args::value the same context as the one with function calls?

Related

Embedded C++11, member function callback

I have some trouble with assigning a callback function-pointer to member function. I have a callback function-pointer like this:
void (*callback)(float arg);
And my class looks like this:
class EXAMPLE_CLASS
{
public:
/*
* Standard Constructor
*/
EXAMPLE_CLASS();
/*
* Standard Destructor
*/
virtual ~EXAMPLE_CLASS();
void test_callback(float arg)
{
y = arg;
}
private:
float y;
};
I want now to assign this callback function-pointer to the member callback function, how can I achieve this?
Edit I want to achieve something like this now:
EXAMPLE_CLASS obj;
callback = obj.test_callback;
I'm not sure I understand your question but, you cannot use a C++ class method as a callback function.
More information here:
How can I pass a class member function as a callback?
If you want to use method void test_callback(float arg); as a call back you need to define this method as a static method of the class and let the prototype of the callback "transport" the class instance it refers to.
Here is a modified version of your code you can use as a template:
class EXAMPLE_CLASS
{
public:
/*
* Standard Constructor
*/
EXAMPLE_CLASS(){};
float y;
/*
* Standard Destructor
*/
virtual ~EXAMPLE_CLASS();
static void test_callback(void* instance, float arg)
{
// retrieve the object
auto obj = static_cast<EXAMPLE_CLASS*>(instance);
obj->y = arg ;
}
};

Mocking Static Method in c++

I just started working on unit testing using googleTest.
I have a situation where I have a static method of one class is calling inside the other class
class A {
public:
static bool retriveJsonData(std::string name, Json::Value& responseJsonData);
}
In other class i am using the Class A retriveJsonData method.
class B {
public:
bool Method1 (std::string name) {
Json::Value sampleJsonData;
return A::retriveJsonData(name, sampleJsonData);
}
Mocking of class A
class MockA : public A {
public:
MOCK_MEHTOD2(retriveJsonData, bool(std::string, Json::Value));
}
Now I have to mock retriveJsonData in Testing of Method2 of class B using EXPECT_CALL.
Please help me to resolve how can I test this situation?
Google Mock's mock types provide ways to check expected calls for non-static member functions, where either virtual function polymorphism or templates can be used as a "seam" to swap in the mock functions for real functions. Which is great if you can design or refactor everything to use one of those techniques. But sometimes it would be cumbersome to get things working that way in messy legacy code or in code using an external library, etc.
In that case, another option is to define a dependency function which is not a non-static member function (so either a free function or a static member) to redirect to some singleton mock object. Assume we have some translation unit (B.cpp) to be unit tested, and it calls some non-member or static member function (A::retrieveJsonData) not defined in that translation unit.
Normally, to unit test B.cpp, we would note its required linker symbols and provide fake definitions for them that stub them out, just to get the object file B.o to link into the unit test program:
// Fake definition:
bool A::retrieveJsonData(std::string, Json::Value&)
{ return false; }
In this case, we don't want that fake definition; we'll define it later to redirect to a mock object.
Start with a mock class specifically for the problematic function calls. If there are other non-static member functions to test the ordinary way, this class is NOT the same as those classes. (If this is needed for more than one function, these mock classes could be done per function, per class and/or one for free functions, per library, one for everything; however you want to set it up.)
class Mock_A_Static {
public:
Mock_A_Static() {
EXPECT_EQ(instance, nullptr);
instance = this;
}
~Mock_A_Static() {
EXPECT_EQ(instance, this);
instance = nullptr;
}
MOCK_METHOD2(retrieveJsonData, bool(std::string, Json::Value&));
private:
static Mock_A_Static* instance;
friend class A;
};
Mock_A_Static* Mock_A_Static::instance = nullptr;
// The function code in B.cpp will actually be directly calling:
bool A::retrieveJsonData(std::string name, Json::Value& responseJsonData)
{
EXPECT_NE(Mock_A_Static::instance, nullptr)
<< "Mock_A_Static function called but not set up";
if (!Mock_A_Static::instance) return false;
return Mock_A_Static::instance->retrieveJsonData(name, responseJsonData);
}
Then just put an object of that type local to a test, or in a fixture class. (Only one at a time, though!)
TEST(BTest, Method1GetsJson)
{
Mock_A_Static a_static;
B b;
EXPECT_CALL(a_static, retrieveJsonData(StrEq("data_x"), _));
b.Method1("data_x");
}
Use A as a template parameter in class B (see Modern C++ Design).
template <class T>
class B {
public:
bool Method1 (std::string name) {
Json::Value sampleJsonData;
return T::retriveJsonData(name, sampleJsonData);
}
}
then in your tests use:
B<MockA> b;
In production code:
B<A> b;
You can't use MOCK_MEHTOD2 with static methods.
You can define a private method in B that just call retriveJsonData:
Class B
{
public:
bool Method1 (std::string name) {
Json::Value sampleJsonData;
return retriveJsonData(name, sampleJsonData); };
private:
bool retriveJsonData(std::string name, Json::Value& responseJsonData) {
return A::retriveJsonData(name, responseJsonData); };
};
Then you can write a test class to be used in your test instead of B:
Class Test_B : public B
{
MOCK_METHOD2( retriveJsonData, bool(std::string name, Json::Value& responseJsonData));
};
This situation is very common in real development. To isolate a target class the gmock is very useful but also very limitted.
However, if you don't want to change any of the class A and B, here is the one of the solution by using "jomock" without changing A and B at all.
// let's say there are class A and B in legacy code.
class A {
public:
static bool retriveJsonData(std::string name, Json::Value& responseJsonData);
}
class B {
public:
bool Method1 (std::string name) {
Json::Value sampleJsonData;
return A::retriveJsonData(name, sampleJsonData);
}
// unit test code below
#include "jomock.h"
TEST(JoMock, staticFnTest)
{
EXPECT_CALL(JOMOCK(A::retriveJsonData), JOMOCK_FUNC(_,_))
.Times(Exactly(1))
.WillOnce(Return(false)); // return false once.
EXPECT_EQ(B::Method1("arg"), false);
}

The fact that the type of function determined in runtime is defined as advantage?

I read that one advantage of using by "inheritance" for generic-code is "the fact that the type of the object determined in runtime", because that allows more flexibility.
I don't understand this point. How it's really allows more flexibility?
If for example I get object from type that derived Base , so that:
class Base{
public:
virtual void method() const { /* ... */ }
};
class D1 : public Base{
public:
void method() const override { /* ... */ }
};
class D2 : public Base{
public:
void method() const override { /* ... */ }
};
And I send to function f (for example) the following object:
Base* b = new D1;
f(b);
Where is the flexibility (What it's defined as advantage that it's done in runtime) ?
Your example isn't demonstrating it, but it could.
f(b) could be
void f(Base* b) {
b->method();
}
Now, the actual method() code that's executed is determined at runtime by the type of the object that's passed in.
How it's really allows more flexibility?
It's more flexible because the author of f(..) doesn't need to know how Base:method() works in any specific case: You can add D3, D4, D5 classes with new implementations of method() without f(..) ever needing to know or change.

How do I refactor two classes with similar functionality?

I have classes with methods with the same names that do the same thing yet they are implemented differently.
Ex:
class converterA {
map(Item1 item1) {
// Implementation details.
}
convert(Item1 item1) {
// Implementation details.
}
translate(Item1 item1) {
// Implementation details.
}
}
class converterB {
map(Item2 item2) {
// Implementation details.
}
convert(Item2 item2) {
// Implementation details.
}
translate(Item2 item2) {
// Implementation details.
}
}
I considered using an interface but the issue is that is that the methods take in different parameters. Yet a template doesn't exactly fit either because Item1 and Item2 operate in different ways. In other words, they don't have common methods so a template doesn't exactly fit either.
Is there a solution here for refactoring the code?
Given your comment "way to... have an interface styled class that can be extended", you might be interested in using templates to express the common "interface":
template <typename Item>
struct Converter
{
virtual void map(Item) = 0;
virtual void convert(Item) = 0;
virtual void translate(Item) = 0;
};
class converterA : public Converter<Item1> {
void map(Item1 item1) final { ... }
void convert(Item1 item) final { ... }
void translate(Item1 item) final { ... }
};
class converterB : public Converter<Item2> {
...same kind of thing...
};
All it buys you though is an expression of the "Converter" interface they share, some compile-time enforcement that the function signatures and names match that (e.g. if you change Converter<> you'll be reminded to update all the derived types), and the ability to handle the derived classes using pointer/references to the template instantiations they derive from (which is not of any ostensible use to you).
I was thinking about using template specialization, but if they both use totally different methods it's not really worth it, although it would be more readable.

Template definition order problem

I've got a simple mixin, which I am mixing in to my other template classes.
template<typename T> class mixin {
static T* null() { return nullptr; }
auto func() -> decltype(null()->func());
};
template<...> class A : public mixin<A<...>> {
....
};
template<...> class B : public mixin<A<...>> {
....
};
template<...> class C : public mixin<A<...>> {
....
};
Now, I've got a problem. One of the mixin functions will return a type which must be deduced depending on the derived type. But when I attempt to use deduction to find this type, the compiler tells me that I am using an undefined type. If I move the definition of mixin to be after the classes, then I won't be able to inherit from it when mixing in. How can I change my classes to allow type deduction in this case?
I don't believe there's any way to make this work. You have a cyclic dependency between the types of each class. A needs the definition of mixin<A<...>> and mixin<A<...>> needs the definition of A.
In my opinion, you would be best just to manually specify the type in the mixin parameters.
For example:
template<typename ReturnType> class mixin
{
auto func() -> ReturnType;
};
template<...> class A : public mixin<int>
{
int func();
};

Resources