Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic templates without function parameters

Can I use variadic templates without using the template parameters as function parameters?

When I use them, it compiles:

#include <iostream>
using namespace std;

template<class First>
void print(First first)
{
    cout << 1 << endl;
}

template<class First, class ... Rest>
void print(First first, Rest ...rest)
{
    cout << 1 << endl;
    print<Rest...>(rest...);
}

int main()
{
    print<int,int,int>(1,2,3);
}

But when I don't use them, it doesn't compile and complains about an ambiguity:

#include <iostream>
using namespace std;

template<class First>
void print()
{
    cout << 1 << endl;
}

template<class First, class ... Rest>
void print()
{
    cout << 1 << endl;
    print<Rest...>();
}

int main()
{
    print<int,int,int>();
}

Unfortunately the classes I want to give as template parameters are not instantiable (they have static functions that are called inside of the template function). Is there a way to do this?

like image 531
Heinzi Avatar asked Apr 23 '12 10:04

Heinzi


Video Answer


2 Answers

template<class First> // 1 template parameter
void print()
{
    cout << 1 << endl;
}

#if 0
template<class First, class ... Rest> // >=1 template parameters -- ambiguity!
void print()
{
    cout << 1 << endl;
    print<Rest...>();
}
#endif

template<class First, class Second, class ... Rest> // >=2 template parameters
void print()
{
    cout << 1 << endl;
    print<Second, Rest...>();
}
like image 139
n. 1.8e9-where's-my-share m. Avatar answered Sep 29 '22 03:09

n. 1.8e9-where's-my-share m.


Make it a type.

template <typename... Ts>
struct print_impl;

template <typename T>
struct print_impl<T> {
    static void run() {
        std::cout << 1 << "\n";
    }
};

template <typename T, typename... Ts>
struct print_impl<T, Ts...> {
    static void run() {
        std::cout << 1 << "\n";
        print_impl<Ts...>::run();
    }
};

template <typename... Ts>
void print() {
    print_impl<Ts...>::run();
}

int main() {
    print<int, int, int>();
    return 0;
}
like image 32
Cat Plus Plus Avatar answered Sep 29 '22 02:09

Cat Plus Plus