我知道我们可以做到以下几点,
template <class CONTAINER>
void f(CONTAINER *c){}
int main(){
std::vector<int> v;
f(&v);
std::set<int> s;
f(&s);
}
然后,我想要一个替代方案(对我的项目来说很方便),如下所示,
template <class CONTAINER>
void f(CONTAINER<int> *c){} // the CONTAINER is the name of a template class
但是,编译器输出
error: ‘CONTAINER’ is not a template
这可能吗?
您正在寻找模板template参数:
#include <set>
#include <vector>
template<template<typename> typename CONTAINER>
void f(CONTAINER<int> *){}
int main(){
std::vector<int> v;
f(&v);
std::set<int> s;
f(&s);
}
“将模板模板参数匹配到兼容参数”是C ++ 17的功能。这不适用于C ++ 14,因为它std::vector
具有多个模板参数。
您需要-frelaxed-template-template-args
使用Clang编译此代码,请参见:功能模板中的模板模板参数和P0522R0如何破坏代码?
另一种方法是将模板模板参数与可变参数模板一起使用,以避免“将模板模板参数匹配到兼容参数”:
#include <set>
#include <vector>
template<class T, template<class, class...> class CONTAINER, class... Args>
void f(CONTAINER<T, Args...> *){}
int main(){
std::vector<int> v;
f(&v);
std::set<int> s;
f(&s);
}
要么
#include <set>
#include <vector>
template<template<class, class...> class CONTAINER, class... Args>
void f(CONTAINER<int, Args...> *){}
int main(){
std::vector<int> v;
f(&v);
std::set<int> s;
f(&s);
}
这适用于C ++ 11。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句