Variadic templates without function parameters

你。 提交于 2020-01-02 02:01:08

问题


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?


回答1:


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...>();
}



回答2:


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;
}


来源:https://stackoverflow.com/questions/10278640/variadic-templates-without-function-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!