I was able to find one question on SO that seems to be asking the same or similar question that I am, but there are no answers :-(
I'd like to place a non-template parameter after a parameter pack. I'm not too familiar on the C++ standard specification for variadic templates / parameter packs, but my common sense assumption tells me that the right-most parameters passed to a function would be filled into placement parameters first, then the rest get filled into the parameter pack. However, I'm not able to get my test code working on either g++ or clang++. Sample code below.
#include <vector>
#include <iostream>
int Subscribe(int channel, int callback)
{
return channel;
}
// This one works fine...
template<typename... T>
std::vector<int> SubscribeMultiple1(int callback, T&&... channels)
{
return {
Subscribe(std::forward<T>(channels), std::move(callback))...
};
}
// This one does not work; all I did was move `int callback` after the parameter pack.
template<typename... T>
std::vector<int> SubscribeMultiple2(T&&... channels, int callback)
{
return {
Subscribe(std::forward<T>(channels), std::move(callback))...
};
}
int main()
{
auto subs = SubscribeMultiple2(1, 2, 3);
for (auto sub : subs)
{
std::cout << "Sub: " << sub << '\n';
}
}
So my first question is, why does the non-template parameter not work after the parameter pack? Am I doing something wrong or is this prohibited by the language?
Secondly, is there any way to get the syntax I'm trying to do? I've oversimplified my sample, but in my real code the callback
parameter is really a std::function<...>
. The idea is I can subscribe to a number of "event IDs", and the callback is defined at the end. Having the callback at the end is better for readability and style. Example:
SubscribeMultiple(EventOne, EventTwo, EventThree, [] {
// Implement callback code here when any of the above
// three events are fired.
});
If I have to have the callback in the front, it's less readable IMHO. So I'm willing to try any workaround to get the syntax and structure I'm aiming for. Thanks in advance.