Template parameters in C++ templates

对着背影说爱祢 提交于 2019-12-01 17:34:55

Pretty sure this is what you're looking for:

template<template<class, class...> class V, class T, class... Args>
void fn(V<T,Args...>& value)
{
    // use value here.
}

Invoked simply as:

std::vector<int> v;
fn(v);

And before you ask, yes, you can do it with templates that need more parameters (like std::map<>, etc), Just make sure Arg... covers the optionals and you specify the mandatory ones you care about. Such as:

#include <iostream>
#include <vector>
#include <list>
#include <map>
#include <unordered_map>
#include <cstdlib>

template< template<class, class...> class V, class T, class... Args>
void fn_seq(const V<T,Args...>& value)
{
    std::cout << __PRETTY_FUNCTION__ << '\n';
    // use value here.
}

template< template<class, class, class...> class C, class K, class V, class... Args>
void fn_assoc(const C<K,V,Args...>& value)
{
    // use value here.
    std::cout << __PRETTY_FUNCTION__ << '\n';
}

int main()
{
    std::vector<int> vec;
    fn_seq(vec);

    std::list<double> lst;
    fn_seq(lst);

    std::map<int, float> m;
    fn_assoc(m);

    std::unordered_map<long, long> um;
    fn_assoc(um);

    return EXIT_SUCCESS;
}

Output

void fn_seq(const V<T, Args...> &) [V = vector, T = int, Args = <std::__1::allocator<int>>]
void fn_seq(const V<T, Args...> &) [V = list, T = double, Args = <std::__1::allocator<double>>]
void fn_assoc(const C<K, V, Args...> &) [C = map, K = int, V = float, Args = <std::__1::less<int>, std::__1::allocator<std::__1::pair<const int, float> >>]
void fn_assoc(const C<K, V, Args...> &) [C = unordered_map, K = long, V = long, Args = <std::__1::hash<long>, std::__1::equal_to<long>, std::__1::allocator<std::__1::pair<const long, long> >>]

There is another thing you can do instead of modifying the function definition, i.e. use template alias to adapt std::vector:

#include <vector>
#include<iostream>

template< 
  template<class> class A, 
  class B
  >
void f(A<B> &value) {
    for( auto & x : value ) {
      std::cout << x << std::endl;
    }
}

template< class T >
using VectorAdapter = std::vector<T>;

int main() {
    VectorAdapter<int> value {1, 2, 3};
    f(value);
}

Vector has 2 template parameters, (the second one is almost never used and has a default allocator type)

template < class T, class Alloc = allocator<T> > class vector;

So it should be:

template<template<class,class> class H, class S,class A>
void f(const H<S,A> &value) {
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!