不带函数参数的变量模板 [英] Variadic templates without function parameters

查看:111
本文介绍了不带函数参数的变量模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用可变参数模板而不使用模板参数作为函数参数吗?



当我使用它们时,它编译:

  #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)
}

但是当我不使用它们时,它不编译和抱怨关于歧义:

  #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>();不幸的是,我想作为模板参数给出的类不是可实例化的(他们有在模板函数内调用的静态函数)。
有这样做吗?

解决方案

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

#if 0
template< class First,class ... Rest> //> = 1模板参数 - 歧义!
void print()
{
cout<< 1<< endl;
print< Rest ...>();
}
#endif

template< class First,class Second,class ... Rest> //> = 2模板参数
void print()
{
cout< 1<< endl;
print< Second,Rest ...>();
}


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?

解决方案

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

这篇关于不带函数参数的变量模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆