C ++模板中的模板参数 [英] Template parameters in C++ templates

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

问题描述

我想使用模板模板参数,类似于此处在这里(以及许多其他地方)。

I am trying to use template template parameters, similar to what is done here and here (and many other places).

#include <vector>

template<template<class> class A, class B>
void f(A<B> &value) {
}

int main() {
    std::vector<int> value;
    f<std::vector, int>(value);
}

$ g++-4.8 -std=c++0x base64.cpp
base64.cpp: In function ‘int main()’:
base64.cpp:9:23: error: no matching function for call to ‘f(std::vector<int>&)’
  f<std::vector, int>(value);
                       ^
base64.cpp:9:23: note: candidate is:
base64.cpp:4:6: note: template<template<class> class H, class S> void f(const H<S>&)
 void f(H<S> &value) {

我缺少什么?

推荐答案

很肯定这是你要找的:

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

只需调用:

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

在你问之前,是的,你可以使用需要更多参数的模板c $ c> std :: map<> 等),只需确保 Arg ... 涵盖可选项,你关心的人。例如:

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;
}

输出

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> >>]

这篇关于C ++模板中的模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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