Member function to a list of pointer - c++

Thanks for giving comments to the following.
Class1 { debug(std::ostream&){} };
int main() {
std::vector<Class1*> list1;
// some work to do
}
Target Platform:
Platform(1): Win 7x64, VS2010
Platform(2): Linux x32, g++ 4.4
Q: What should be the correct way to pass "std::cout" to following statement?
std::for_each(list1.begin(),
list1.end(),
"afunction(&Class1::debug, std::cout)");
I previously used "std::cout" inside the debug() function, but later consider to give flexibility for the output of debug message.
Edit: More information: if functor objects is the way to go, how should I implements the functor to cope with multiple classes (those classes have no relationship except the same "debug" function signature)?
Edit(2): Using "std::for_each", is it possible to destroy all objects in list1 by invoking the corresponding destructor for each class directly? (e.g. for_each(l.begin(), l.end(), "Class::~Class1");
Edit(3): As per "pmr" suggested, I make the statement as
std::for_each(l.begin(),
l.end(),
std::bind2nd(std::mem_fn(&Class1::debug), out) );
It compiles and run correctly on linux platform, but failed on VS2010, the code for Class1::debug is
void Class1::debug(const std::ostream& out)
{
out << "some text" << someVar << "some text" << std::endl;
}
The VS error msg is
error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'const std::ostream' (or there is no acceptable conversion)
Any cue?
[Closed]
I now implemented the overloaded operator << for my classes, and the use of debug print function is closed. Thanks very much for all hints given.

Since you are using g++ 4.4 you can't use lambda expressions which would be the first choice (later versions support them, MSVC does as well).
So you need a functor. A functor is a function object, that is a class (or struct) that implements operator(). Like this:
class Debug
{
public:
Debug(ostream& os) : _os(os)
{ }
void operator()(Class1* instance)
{
// will print the pointer, replace with user code
os << instance << endl;
}
private:
ostream& _os;
};
Use like this:
Debug d(cout);
std::for_each(list1.begin(), list1.end(), d);

use lambda instead of function pointers. This is a feature of C++11x and you need to include a flag for compiler to recognise lambda.
std::for_each(list1.begin(), list1.end(), [&debug, &cout]
{
// implementaion
}
);

As GCC does not support lambdas until 4.5, the clearest solution is out of the question.
The second easiest solution when you want to use a lot of generic algorithms is Boost.Lambda http://www.boost.org/doc/libs/1_49_0/doc/html/lambda.html:
for_each(list1.begin(), list.end(), _1->debug(cout));
And finally, the tedious functor solution:
class Output
{
public:
explicit Output(ostream& ios) : os(&ios)
{
}
void operator()(Class1* obj)
{
obj->debug(*os);
}
private:
ostream* os;
};
for_each(list1.begin(), list1.end(), Output(cout));
Personally I think that without C++11 lambdas or Boost Lambdas, for_each is more pain than it's worth. Might as well do a simple loop:
for (vector<Class1*>::iterator it = list1.begin(); it != end; ++it)
(*it)->debug(cout);

C++03:
#include <vector>
#include <functional>
#include <iostream>
#include <algorithm>
struct Foo {
void debug(std::ostream&) {}
};
int main()
{
std::vector<Foo*> foos;
std::for_each(foos.begin(), foos.end(),
std::bind2nd(std::mem_fun(&Foo::debug), std::cout));
return 0;
}
Please note that the binders have been deprecated and boost::bind or
C++11 should be favored. You should really get a newer compiler.

Related

Getting active value in std::visit without knowing which value is active

I want to get the active value in a std::variant without knowing which one is active. I thought i could write a template visitor and use std::visit but it doesn't work.
#include <variant>
#include <string>
#include <iostream>
struct Visit_configuration {
template<typename Data_type>
Data_type operator()(Data_type& t) const
{
return t;
}
};
int main()
{
std::variant<int, std::string> v;
v = "hello";
std::cout << std::visit(Visit_configuration(), v); // expect "hello"
std::cin.get();
}
MSVC doesn't compile and throws:
error C2338: visit() requires the result of all potential invocations
to have the same type and value category (N4741 23.7.7
[variant.visit]/2).
note: see reference to function template instantiation 'int
std::visit&,0>(_Callable
&&,std::variant &)' being compiled
So how to fix this?
edit: I want to use the obtained value maybe also for other so putting cout in the template isn't what im looking for.
Ask yourself the question:
What is the return type of std::visit if you don't know what part of the variant is active?
That is the question that the compiler must answer. And the answer can't be "it depends" - you (as in, the compiler) must decide on exactly one type at compile-time. The visit call cannot possibly return different types at runtime.
If you want to work with different types "at runtime", you must be in a function templated on the type you want to work with. In other words, there must be different functions (or function template instantiations) to handle the "write an int to cout" and "write a string to cout" cases. You cannot do this in the same (non-templated) function.
The straightforward solution here is thus to put the std::cout << into your templated visitor function - that's the point of visiting: Specifying what is supposed to happen in each case.
If you want to "use the obtained value maybe also for [some] other [purpose]", then that "other purpose" should also be part of the/a visitor. Only then can you have that "other purpose" handle the different cases at once (e.g. in a templated function). Otherwise you must decide at compile-time already which type shall be used - the compiler is not going to leave that choice open for later (run time).
Return type of visitor function should be identical.
Create printer visitor instead:
struct PrinterVisitor {
template<typename T>
void operator()(const T& t) const
{
std::cout << t;
}
};
int main()
{
std::variant<int, std::string> v;
v = "hello";
std::visit(PrinterVisitor{}, v); // expect "hello"
}
And in your case, you can even have lambda:
int main()
{
std::variant<int, std::string> v;
v = "hello";
std::visit([](const auto& t){std::cout << t;}, v); // expect "hello"
}

C++ multiple sets of parameters with their own parentheses on function call?

I've been coding in C/C++ for a while and I'm using the https://github.com/jarro2783/cxxopts library. The library uses the add_options() function to grab it's configuration, like this:
options.add_options() ("option1", "Description1") ("option2", "Description2");
And you can add an arbitrary number of options.
It came as a surprise that this is valid C/C++ and works; I have never seen something like that.
How are they doing it? Is there a name for this syntax?
options.add_options() returns an object.
That object has the function call operator overload that takes two strings, which most likely looks like
ObjectType& operator()(std::string const& option, std::string const& value);
which allows you to chain the function calls.
Here's a simple program that demonstrates the concept.
#include <iostream>
struct Foo
{
Foo& operator()(int x)
{
std::cout << "Got " << x << std::endl;
return *this;
}
};
struct Bar
{
Foo getFoo() { return Foo(); }
};
int main()
{
Bar b;
b.getFoo()(10)(200)(30);
}
Output of the program:
Got 10
Got 200
Got 30
That line in main is equivalent to:
Foo foo = b.getFoo();
foo(10);
foo(200);
foo(30);
PS
Personally, I find that style of coding a bit cryptic and best avoided. I would rather see:
auto& option = options.add_options();
option.addOption("option1", "Description1");
option.addOption("option2", "Description2");
That's a lot clearer to understand, IMO.

How do I pass a function as parameter?

What is the fastest and shortest way to pass a function as parameter of another function without using other libraries other than the std one in just one line?
I mean let's say we have a function forloop(int x, *) {...} that run a for loop from 0 to x running the * function; the function call should be something like: forloop(3, **() { std::cout "Hi!"; });.
PS: * and ** are just placeholders for the function-by-argument type and the way to pass the function as argument.
C++11 provides anonymous functions:
forloop(3, []{ std::cout "Hi!"; });
Example:
#include <iostream>
#include <functional>
void forloop(int times, std::function<void()> f) {
for(int i = 0; i < times; i++) {
f();
}
}
int main() {
forloop(3, [] () { std::cout << "Hello world"; });
}
Try "pointers to member functions" if your function is a member of any class.
You are looking at several options.
function pointers, the C style way
std::function which is part of C++ TR1 and C++11
use functors and std::ptr_fun to adapt your function
The syntax you are showing is only going to work with C++11. Earlier C++ versions don't offer the possibility to define an anonymous function.

std::ostream::operator<< not defined for std::string?

I have stumbled upon an error for which I cannot grasp the reason.
I think it basically gets down to this error:
error: no matching function for call to ‘std::basic_ostream<char>::operator<<(const std::basic_string<char>&)’
I looked into specification on www.cplusplus.com and indeed it says there is no definition for std::ostream::operator<< with std::string as an argument.
My question is, what happens when one writes std_ostream_instance << std_fancy_string;. I believe it is one of the most common invocations ( e.g. std::out << std::string("Hello world!") ) next to const char*.
The error originates from these lines:
template<typename T>
void Log::_log(const T& msg)
{ _sink->operator<<( msg ); }
_sink is defied as std::ostream*
There are some wrapping functions around but it breaks here.
I think I could work around by writing
template<>
void Log::_log<std::string>(const std::string& msg) {
_sink->operator<<( msg.c_str() );
}
since there is ostream& operator<< (ostream& out, const unsigned char* s ); defined by default.
I just see no reason why it is not guessed automatically since it clearly works in simple use like cout << any_std_string.
Not sure if this is relevant but I want to be able to pass down through my log functions anything than can be handled by std::ostream. I used explicit non-templated declarations but decided to move to template for log(const T& anything_to_log) to refacator it. It seemed plain stupid to have 5+ overloads. I get the error when I try compiling something like Log::log( std::string("test case") ).
It looks like something stupid-simple but I cannot get it on my own. Tried to google and search stack to no avail.
With regards, luk32.
PS. I checked the work-around and it works. Why it's not implicitly done ?
operator << overloads are not members of ostream. They are freestanding functions, for example
ostream& operator << ( ostream& out, const basic_string<T>& bs );
Try
template<typename T>
void Log::_log(const T& msg)
{ *_sink << msg; }
The std::string version is not a member function, so can't be called as a member of _sink. Try it this way to pick up both member and non-member versions (in fact it is unlikely you will need the member versions at all anyway):
#include <iostream>
#include <string>
int main()
{
std::ostream * os = &std::cout;
std::string s = "Hello\n";
// This will not work
// os->operator<<(s);
(*os) << s;
return 0;
}
Or better yet would be to store _sink as a reference, and output exactly as you normally would to cout.

Duplicating C/C++ functions at compile time

If I have a function A(), I am interested in finding a convenient method to create a function B() that has the exact same functionality as A(), differing only in name. The new function would be for a one-time use. The intent is to differentiate between calls to the same function in a somewhat primitive sampling profiler, and the duplicated function would only be used in this context. That is, it would never touch production code and only be used for tinkering.
First guess would be a macro that declares a function named B and creates an inlined call to A() inside of it. The problem here is that I'm not aware of a method in GCC to force an arbitrary function call to inline; it seems all inlining options are for function declarations rather than calls.
There may be some esoteric way to do it with templates, or possibly by tricking the compiler into inlining. I'm not sure it's possible. Any thoughts? Unfortunately the new C++ standard is not available, if it would make a difference.
Using templates
template<int x>
void A()
{
// ..
}
int main()
{
A<0>();
A<1>();
return 0;
}
Update
The compiler can be too smart and create only one body for A<0> and A<1>. At least Visual C++ 2010 does it in Release mode. To prevent it, just use the template parameter inside the function template body in logs or asserts. For example,
#include <iostream>
template<int x>
void A()
{
::std::cout << x << std::endl;
// ..
}
int main()
{
A<0>();
A<1>();
auto v0 = A<0>;
auto v1 = A<1>;
::std::cout << v0 << std::endl;
::std::cout << v1 << std::endl;
::std::cout << (v0 == v1) << std::endl;
return 0;
}
This works using templates:
#include <iostream>
template<typename T>
void foo() {
static int x = 0;
std::cout << &x << std::endl;
}
int main(int argc, char **argv) {
foo<int>();
foo<float>();
return 0;
}
If you execute that, you'll see two different values printed, reflecting the compiler generated code for both calls, even though the template parameter is unused. nm on the object file confirms this.
If this is a one-time debug hack, then why not:
#define A_CONTENT \
... // whatever
void A()
{
A_CONTENT
}
void B()
{
A_CONTENT
}
...
A(); // Call to A
B(); // Call to B
Macros are generally grim, but we're not talking about production code here, so who cares?
Having been down this road myself, the short answer is that even if you get the compiler to emit two identical duplicates of a function, the optimizing linker will notice that they're identical and fold them back together into one implementation. (And if you've turned off optimization in the linker, then your profile isn't valid anwyay).
In the context of a sampling profiler, I've found the easier approach is to make two tiny wrappers for the function instead:
void Func() { .... }
_declspec(noinline)
void A_Func( return Func(); }
void B_Func( return Func(); }
void C_Func( return Func(); }
Then when your profiler samples the callstack, you'll be able to differentiate between the different callsites of this function in a very straightforward way..
You could always define a macro, for example in Chromium we do the following to reuse code:
#define CHROMEG_CALLBACK_1(CLASS, RETURN, METHOD, SENDER, ARG1) \
static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, \
gpointer userdata) { \
return reinterpret_cast<CLASS*>(userdata)->METHOD(sender, one); \
} \
\
virtual RETURN METHOD(SENDER, ARG1);
And we call them like:
CHROMEGTK_CALLBACK_1(PageActionViewGtk, gboolean, OnExposeEvent, GdkEventExpose*);
CHROMEGTK_CALLBACK_1(PageActionViewGtk, gboolean, OnButtonPressed, GdkEventButton*);
You can do something similar to do what you wanted. The above example shows us using two different implementations but with one common code base. For GTK callbacks.
It's a little unclear what you're really trying to do, but a really ugly solution would be to declare the body of A as a macro and then you can "inline" this macro within whatever functions you like.
Also, macros are evil. Never use them unless you really have to.
Why do you care so much about inlining it? If you create a wrapper function, there is a pretty good chance the compiler will inline it anyway. At the very least, you're unlikely to get a function frame constructed.
C++11 also lets you do this:
void A() {
...
}
...
auto B = [] () -> void { A(); };
You can now use B syntactically as though it was a function wrapping A.