I'm very new to meta-programming and I was trying to play around with variadic templates. I've searched a lot on StackOverflow and came across multiple solutions for my problem but I couldn't seem to make them work. The code I have is the following:
template <typename TA, typename... TB>
class A
{
public:
inline long long f()
{
// 6 is just a placeholder, the value
// comes from a dummy object which is a class member
return g<TB...>(6);
}
[...]
private:
template <typename Head, typename Head2, typename ...Tail>
inline long long g(long long x)
{
return (&Head::instance())->external_function(g<Head2, Tail...>(x));
}
template<typename Head>
inline long long g(long long x) {
return (&Head::instance())->external_function(x);
}
inline long long g(long long x) {
return x;
}
[...]
Where TB can be 0 or more elements.
So what I was trying to achieve is to call a method external_function in cascade which I know every element inside TB has defined.
It works if TB has one element, but if TB is empty, what I get is that I have no function matching g<>.
Then I tried to redefine the three overloaded functions as follows
template <typename Head, typename ...Tail>
inline long long g(long long x)
{
return (&Head::instance())->external_function(g<Tail...>(x));
}
template<typename Head>
inline long long g(long long x) {
return (&Head::instance())->external_function(x);
}
template<typename = void>
inline long long g(long long x) {
return x;
}
But still no luck.
So what I tried again was to use two specialised functions, one that accepts one or more arguments and the other that is called only when there are zero arguments
template <typename Head, typename ...Tail>
inline long long g(long long x)
{
return (&Head::instance())-> external_function(g<Tail...>(x));
}
template<typename... Tail>
inline long long g(long long x) {
return x;
}
But again, what I get is that this last solution only works if TB is empty. If it contains at least one element I get an error about an ambiguous call.
I'm getting lost with variadic functions and their base cases also because their usage has changed a lot during the years with C++11, C++17 and C++20. I've seen that fold expressions can solve the problem and make the code more readable, but I had no luck trying to use them for cascade calls.
Really hope someone can help me shed light on this.
Edit: For project reasons, I'm stuck with C++14 and below.