通过模板参数号重载模板类 [英] Overloading template classes by template parameter number

查看:121
本文介绍了通过模板参数号重载模板类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以有多个版本的同一类,只有在他们采取的模板参数的数量不同?

Is it possible to have multiple versions of the same class which differ only in the number of template arguments they take?

例如:

template<typename T>
class Blah {
public:
    void operator()(T);
};

template<typename T, typename T2>
class Blah {
public:
    void operator()(T, T2);
};

我试图模仿functor类型的东西,可以接受可变数量的参数

I'm trying to model functor type things which can take a variable number of arguments (up to the number of different templates that were written out).

推荐答案

最简单的答案是只有一个模板,您要支持并使用void作为默认类型,除了第一种类型。然后你可以根据需要使用部分特化:

The simplest answer would be to have just one template, with the maximum number you want to support and use void for a default type on all but the first type. Then you can use a partial specialization as needed:

template<typename T1, typename T2=void>
struct foo {
    void operator()(T1, T2);
};

template <typename T1>
struct foo<T1, void> {
     void operator()(T1);
};

int main() {
   foo<int> test1;
   foo<int,int> test2;
   test1(0);
   test2(1,1);
}

这篇关于通过模板参数号重载模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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