how to pass sprtinf function as a parameter

hi just wondering if someone could give me an example on how to pass a std sprintf function into a parameter of a function thanks.

So the function I want it able to do is this.

_log(sprtinf(buffer," %s some error %s",time, done),para1,para2);

just wondering if this is possible or even this will do.

_log(prtinf(" %s some error %s",time, done),para1,para2);

thank-you
1
2
3
4
5
void MyFunc(int MyParam, int(*PrintFunc)(char*, const char*, ...) = 0, char *buffer = 0)
{
    //code
    if(PrintFunc && buffer) PrintFunc(buffer, "%d", MyParam);
}
1
2
MyFunc(7);
MyFunc(14, &sprintf, buffer);
Not quite the way you wanted...hard to do without using C++11 features, and even then it's not how you would want.


But why not this?
1
2
3
4
5
void MyFunc(int MyParam, std::string *s = 0)
{
    //code
    if(s) *s = (std::ostringstream() << MyParam).str();
}
1
2
3
MyFunc(7);
std::string str;
MyFunc(14, &str);
Last edited on
Thanks for the replies,

Just wondering is it possible to do this in c++

Like concatenate strings at function parameter level for example.

_log(current_time += this->get_some_variable, para2,para3);

rather then have sprintf function as parameter.

I came up with this just wondering is there any side effect in the long run

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

//header.h

#define _CHAR_ char _buf_[200]
#define _CHAR1_ char buf[100]
#define PRINT(_CHAR_ , _CHAR1_ ) (int (*) (const char*, ...))printf(_CHAR_,_CHAR1_)


//Logs_.h

 void set_log_(int (*PrintFunc)(const char* format, ...),int category, int id);

//lLogs_.cc

void Logs_::set_log_(int (*PrintFunc)(const char* format, ...),int category, int id)
{
// implementation for para 2, para3
}


//main.cc

#include "header.h"
#include "Logs_.h"

int main(void)
{
   Logs_ logs_;
   

  logs_.set_log_(PRINT("hello %s",utilities::get_time_for_events().c_str()),1,1);

}



that works for me like what I wanted, just wondering if this will cause me problems later

thanks
vietory wrote:
Thanks for the replies,

Just wondering is it possible to do this in c++

Like concatenate strings at function parameter level for example.

_log(current_time += this->get_some_variable, para2,para3);

rather then have sprintf function as parameter.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>

int main()
{
    std::string a ("Hello, ");
    std::string b = "World!";
    std::cout << a << b << std::endl;
    std::cout << a + b << std::endl;
    std::cout << a += b << std::endl;
    std::cout << a << std::endl;
    std::cin.ignore();
}
Hello, World!
Hello, World!
Hello, World!
Hello, World!
Topic archived. No new replies allowed.