1

assume I have the following function

int watchVar(const char* var, const char* descriptor,
            Color (*colorfunc)(const char* var) = yellowColorFunc)

with

Color yellowColorFunc(const void* var){
    return Color::yellow();
}

I want to overload watchVar to accept functions whos parameters are char, int, float, etc, but do not want to create a default color function for each type.

g++ gives this error:

xpcc::glcd::Color (*)(const char*)' has type 'xpcc::glcd::Color(const void*)

Is there another way besides declaring colorfunc to take a void pointer and forcing the caller to cast the argument later himself?

Thanks

6
  • 3
    Please define "won't compile". Some compilation error would help. Commented Aug 6, 2013 at 21:50
  • -1 (it's only 2 rep points anyway) for not providing the compiler error message. Commented Aug 6, 2013 at 21:53
  • @David downvotes on questions have been free of charge for quite some time now. Commented Aug 6, 2013 at 21:56
  • error: default argument for parameter of type xpcc::glcd::Color (*)(const char*)' has type 'xpcc::glcd::Color(const void*) Commented Aug 6, 2013 at 21:57
  • @jrok: Is it not -2 rep for the person that gets the downvote? Commented Aug 6, 2013 at 22:10

2 Answers 2

4

the function pointer is declared const char * but the yellowColorFunc is declared const void *

Sign up to request clarification or add additional context in comments.

2 Comments

I did that on purpose, so I could reuse yellowColorFunc for int,float etc.
@user765269: This is the classic XY problem. You are asking how to improve your solution to a problem of which everyone is unaware. Take the time to formulate the real problem that you need to solve.
2

Your problem is that your declaring a function pointer taking a const char * but yellowColorFun takes a const void *. If c++11 is available you can use std::function like so:
auto colorFunc = std::function<int(const char *,const char *,std::function<Color(const char*)>)>();

You said in a comment that you wanted to use the function for int,float and others, what your should do in that situation is use a templated function, you really don't wanna use void*'s in c++ very often.

4 Comments

Problem with templates is that I need the type for casting later, because the variable is printed out. RTTI is not available, this code is supposed to be embedded c++. Is there a typeid equivalent at compile time?
@user765269 why do you need RTTI ints and floats support most of the same functions
@user765269 The compile time equivalent of RTTI and typeid is templates.
You are right, I was overthinking the template version, that should totally do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.