多个函数使用同一个模板? [英] Multiple functions using the same template?

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

问题描述

是否可以在同一个模板中包含多个函数而不是重写模板两次?就像你在写:

Is it possible to include more than one function in the same template instead of rewriting the template twice? Like if you were writing:

template <typename T>
void A() {
    //...
}

template <typename T>
void B() {
    //...
}

那些不是同一个函数,但它们共享一个相似的模板(使用泛型类型T).有没有办法只初始化模板一次?

Those are not the same function, but they share a similar template (using the generic type T). Is there a way to initialize the template only once?

推荐答案

将它们分组在一个类模板中可以实现这一点.

Grouping them inside a class template would achieve that.

template <class T>
struct Functions {
    static void A() { /*...*/ }
    static void B() { /*...*/ }
};

但是,您无法从函数的参数中推导出 T,并且调用语法更长:

However, you lose the ability to deduce T from the functions' arguments, and the calling syntax is longer :

Functions<double>::A();

这篇关于多个函数使用同一个模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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