使用模板参数实例化模板类
Instantiating template classes with template parameters
我有三个类:
//Template class for function 1
template<class P> class wrap4{
P p;
public:
wrap4(P&& p1) : p(std::forward<P>(p1)) {}
double f(double x){
return p.FN(x);
}
};
//Simple concrete parameter
struct Parameter{
double FN(double x){
return x;
}
};
//Method used in the program
template<class Function> class B {
Function F;
public:
B(Function && f) : F(std::forward<Function>(f)) {}
double use(double x){
return F.f(x);
}
};
template<class Function> B<Function> make_B(Function && F){ return B<Function>{std::forward<Function>(F)}; }
template<class P> B<P> make_wrap4(P && F){ return B<P>{std::forward<P>(F)}; }
基本上,我想把wrap4
插入B
,但要做到这一点,我必须用Parameter
实例化它。我试过以下几种:
auto A = make_B(make_wrap4{Parameter p});
但这不起作用,我得到了编译错误
error: conversion from 'B<B<Parameter> >' to non-scalar type 'B<wrap4<Parameter> >' requested
当然,这是一个愚蠢的例子,因为我知道我可以用Parameter
实现B
,但从长远来看,我当然会尝试做一些更复杂的事情,我真的需要一个B
来接受一个不允许默认构造函数作为参数的模板类。
我需要在这里实现一个模板模板参数吗?
您有一个副本&粘贴错误,您应该能够从错误消息中发现:
template<class P> B<P> make_wrap4(P && F){ return B<P>{std::forward<P>(F)}; }
应该是
template<class P> wrap4<P> make_wrap4(P && F){ return wrap4<P>{std::forward<P>(F)}; }
// ^^ here ^^ and here
然后应该像函数一样调用make_wrap4
,即不使用初始值设定项列表。
附带说明:您没有三个类,您有一个类和两个类模板。它也不是模板类,正如wrap4
的注释所述。
wrap4
是类模板wrap4<int>
和wrap4<Parameter>
是类,您可以通过实例化类模板来获得它们。有些人也会将此类类称为模板类
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如果模板参数是另一个模板的实例化,则键入特征测试
- 如何在模板函数中实例化其长度使用模板参数的数组
- 函数在可变参数模板的实例化期间不可见
- 实例化模板时,我是否必须显式显示参数包中的类型?
- 从模板参数包实例化的访问类实现
- C++ 可变参数模板实例化深度超过最大值 900
- 与参数匹配的友元模板函数实例化
- 有没有办法根据命令行参数定义数组大小?运行时与编译时实例化?
- 在编译时检查未实例化的类模板是否继承自其第一个模板参数
- 实例化模板参数的参数包
- SFINAE 和模板函数实例化:为什么在启用了 SFINAE 类型的函数参数中使用模板参数时无法推断模板参数?
- 非类型引用参数可以在运行时修改,这是否意味着模板可以在运行时实例化?
- 无法实例化抽象类,但类不是抽象/派生方法的参数
- 有没有办法将一对元组剥离为可变参数模板类型或实例化具有可变参数类型的东西?
- unique_ptr 使用尚未定义的参数进行实例化不会导致错误
- 根据运行时参数避免模板实例化的代码重复
- 编译时检查是否有两个具有相同模板参数的模板实例化
- 如何编写模板重载函数,并在模板参数不允许实例化某个类时触发回退
- 在不使用"new"的情况下实例化参数参数中的对象