Call variable function using variable template
Consider the following code:
template<typename T, typename... Args>
void foo(const Args&... args)
{
//...
}
template<typename... Args>
auto fooChar = foo<char, Args...>;
template<typename... Args>
auto fooInt = foo<int, Args...>;
To be able to use these variable templates, I need to explicitly enter the template parameters, for example:
fooChar<int, char, const char*>(5, 'a', "bar");
However, in a standard variational function call, the template parameters are implicitly inferred based on the actual type of the function parameters. In other words, I would like to be able to use variable templates like this, but an additional level of indirection seems to limit this:
fooChar(5, 'a', "bar");
Obviously, I could just define simple wrapper functions instead of template variables, like this:
template<typename... Args>
void fooChar(const Args&... args)
{
return foo<char>(args...);
}
template<typename... Args>
void fooInt(const Args&... args)
{
return foo<int>(args...);
}
But overall, it just feels cumbersome and less convenient. So, is there a way to achieve the same result when using variable templates? If not, why can't the compiler "pass" the parameters to the aliased function and thus infer the variadic types?
source to share
You can wrap foo()
in a struct:
template <class T>
struct fooWrapper {
template <class... Args>
void operator()(Args const&... args) const {
foo<T>(args...);
}
};
Now, make your variable templates instances of this wrapper:
fooWrapper<char> fooChar;
fooWrapper<int> fooInt;
With the added bonus that you can pass fooChar
to a function template as it is not itself a function template.
source to share
Required shell:
#include <utility>
template<typename T, typename... Args>
void foo(const Args &&... args)
{
//...
}
template<typename ...Args>
inline void fooChar(const Args && ...args)
{
foo<char>(std::forward<Args>(args)...);
}
Hopefully your compiler will optimize the function call.
source to share