0

I'm trying to create a simple template engine, an engine that takes a pattern and some variable and produces a string output. This is the idea:

const char * pattern = ReadPattern(); // pattern is like "%s in %s ft"
vector<const char *> variable = ReadVariable(); // variable is like "6", "5".

How can I call printf function with them? Ideally I can do printf(pattern, variable[0], variable[1]); But because both pattern and variable are not known until runtime, I don't even know the number of variable. To my understanding, constructing a va_list programmingly is a not portable.

Please help, Thank you!

3

1 Answer 1

1

If you have an upper bound on the number of vector elements, it is relatively straight forward. Suppose the upper bound is 3:

int printf_vector(const char *p, vector<const char *> v) {
    switch (v.size()) {
    case 0: return printf(p);
    case 1: return printf(p, v[0]);
    case 2: return printf(p, v[0], v[1]);
    case 3: return printf(p, v[0], v[1], v[2]);
    default: break;
    }
    return -E2BIG;
}

If you have no upper bound, then this is a bad idea.

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

1 Comment

In theory, you could look at the assembly output for the code, and figure out how to write an inline assembly loop to push the vector elements on to the stack and call printf.

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.