本文介绍了可能需要参考的C ++模板化函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了简化一点,我有一个函数,如下所示:

I have a function that, to simplify a bit, looks like this:

template<typename T>
T DoStuff(const vector<T>& data) {
    T ret_data;
    for (const T datum : data) { /* ... */ }
    return ret_data;
}

通常T是一个整数或字符串。如果这不是模板代码,则在该for循环中使用 const string& ,但使用 const int 。并且,当然,我可以只使用int引用( const T& datum )。但是我很好奇这是否有一个成语。

Usually T is an int or a string. If this weren't templated code, I'd use a const string& but a const int in that for loop. And, of course, I can just use int references (const T& datum). But I'm curious if there's a proper idiom for this.

我很清楚在我的特定情况下这无关紧要。

I am well aware that in my particular case it won't matter. This is purely pedagogical today.

推荐答案

对此没有约定或成语,不是。一般来说,我只会接受∀ T ,但是如果您愿意的话,您可以专注于内置类型。

There is no convention or idiom for this, no. Generally I'd just accept references ∀ T, but you can specialise for the built-in types if you really want.

这篇关于可能需要参考的C ++模板化函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 08:39