模板模板C ++函数 [英] Template Template C++ Function
问题描述
如何编写一个对任意类型的任意容器进行操作的模板函数?例如我如何概括这个虚拟函数
template< typename Element>
void print_size(const std :: vector< Element>& a)
{
cout< a.size()< endl
}
到
template< template< typename> class Container,typename Element>
void print_size(const Container< Element>& a)
{
cout< a.size()< endl
}
以下是典型用法
std :: vector< std :: string> F;
print_size(f)
这会产生错误
tests / t_distances.cpp:110:12:error:没有匹配的函数调用'print(std :: vector< std :: basic_string< char>& ;)。我猜我必须告诉编译器一些更具体的关于什么类型是允许的。
调用的模板使用变体是什么?
是否有特定原因要使用模板模板?为什么不是这样?
模板< typename Container>
void print_size(Container const& a)
{
cout<< a.size()< endl
}
一般来说,模板模板不值得。在你的特殊情况下,肯定没有用它们,如果你真的需要访问成员类型,我建议你常规做法和使用元功能( typename Container :: value_type
在这种情况下)。
How do I write a template function that operates on a arbitrary container of a arbitrary type? For example how do I generalize this dummy function
template <typename Element>
void print_size(const std::vector<Element> & a)
{
cout << a.size() << endl;
}
to
template <template<typename> class Container, typename Element>
void print_size(const Container<Element> & a)
{
cout << a.size() << endl;
}
Here is a typical usage
std::vector<std::string> f;
print_size(f)
This give error
tests/t_distances.cpp:110:12: error: no matching function for call to ‘print(std::vector<std::basic_string<char> >&)’. I'm guessing I must tell the compiler something more specific about what types that are allowed.
What is this variant of template-use called and how do I fix it?
Is there a specific reason for you to use a template template? Why not just like this?
template <typename Container>
void print_size(Container const& a)
{
cout << a.size() << endl;
}
In general, template templates aren’t worth the trouble. In your particular case, there certainly is no use for them, and if you really need to access the member type, I suggest you bow to common practice and use a metafunction (typename Container::value_type
in this case).
这篇关于模板模板C ++函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!