我想写一个像这样的C++函数:
template <T<int> >
void printIntegers(T<int> ints) {
for (int i: ints) printf("%d ", i);
}
因为我希望T
是Vector
或List
或任何其他STL容器。 模板参数应该怎么写?
别想多了。
template <typename Container>
void printIntegers(const Container& container)
{
static_assert(std::is_same_v<typename Container::value_type, int>);
for (const auto& el : container)
{
printf("%d ", el);
}
}
或者只是:
template <typename Container>
void printThings(const Container& container)
{
for (const auto& el : container)
{
std::cout << el << ' ';
}
}
您可以使用一个模板模板参数作为参数:
template <template <typename...> typename Container>
void printIntegers(Container<int> ints) {
for (int i : ints) std::printf("%d ", i);
}
请参阅https://en.cppreference.com/W/cpp/language/template_parameters#template_template_parameter
正如其他答案已经表明的那样,通过常量引用可能是更好的,而且无论如何,可能还有更好的方法来做你的例子。
您只需使用一个模板模板参数(这里有模板模板参数小节),如下所示:
template < template < typename > typename T > void printIntegers( T<int>& container )
{
for ( int el: container ) { std::cout << el << " " ; }
std::cout << std::endl;
}
int main()
{
std::vector<int> i{1,2,3,4};
std::list<int> l{7,8,9,10};
printIntegers( i );
printIntegers( l );
}
一些提示:在您的代码中,通过将容器传递到您的函数中,您进行了复制而不是引用。 这将通过复制内容产生大量的开销。 编译器可能会对其进行优化,但您应该使用引用来编写它,以保证不会因为副本而浪费您的内存。