2

Is it possible to generate arguments based on int type of a template ?

I would like to generate something like

template<int num>
void func(int g,...){}

if num=10 then I would like my function becomes void func(int g, int gg, ....., int gggggggggg);

I would love to know if this is feasible. Thank you.

0

2 Answers 2

2

Variadic function arguments a la <cstdarg> are not typesafe, and they're not a good idea in C++. If you have C++11, you can use variadic templates for much better results.

Be that as it may, if you want to go with variadic function arguments, you have to tell the function which arguments there are and how big they are. Traditionally, you would pass that information in one of the arguments (like printf does). If you wanted to, you could use the template parameter for that effect, but since you have to have at least one non-variadic argument anyway, there's really no need. Most importantly, making the function a template will instantiate a different piece of code for every N!

So, to summarize: Don't use variadic functions. If you have to use variadic functions, don't use templates with them.

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

Comments

1

If you don't have access to variadic macros through C++11, you could instead try an external metaprogramming tool like PUMP.

Be warned that this will complicate your build process, because you are now using an extra tool to translate from something that is like C++ source to something that actually is valid C++ source.

You could also look into something like the Boost Preprocessor library, which avoids the need for an extra tool but is more cumbersome to work with.

Comments

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.