gpt4 book ai didi

c++ - C++ 模板中的模板参数

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:07:16 25 4
gpt4 key购买 nike

我正在尝试使用模板模板参数,类似于所做的herehere (以及许多其他地方)。

#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);

在你问之前,是的,你可以用需要更多参数的模板来做(比如 std::map<> 等),只要确保 Arg...涵盖可选项,您指定您关心的强制性选项。如:

#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++ - C++ 模板中的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21569216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com