使用模板参数实例化模板类

Instantiating template classes with template parameters

本文关键字:实例化 参数      更新时间:2023-10-16

我有三个类:

//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>,您可以通过实例化类模板来获得它们。有些人也会将此类类称为模板类