Plamen
Plamen

Reputation: 660

Instantiating template classes with template parameters

I have three classes:

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

Basically, I want to plug wrap4 into B, but to do so I have to instantiate it with Parameter. I've tried the following:

auto A = make_B(make_wrap4{Parameter p});

but this doesn't work, I get the compiler error

error: conversion from 'B<B<Parameter> >' to non-scalar type 'B<wrap4<Parameter> >' requested

Of course, this is a silly example because I know I can just implement B with Parameter, but of course I'm trying to do something more complicated in the long run where I really need a B to take a template class which doesn't admit a default constructor as an argument.

Do I need to implement a template template parameter here?

Upvotes: 0

Views: 105

Answers (1)

Arne Mertz
Arne Mertz

Reputation: 24576

You have a copy&paste error you should be able to spot from the error message:

template<class P> B<P> make_wrap4(P && F){ return B<P>{std::forward<P>(F)}; }

should be

template<class P> wrap4<P> make_wrap4(P && F){ return wrap4<P>{std::forward<P>(F)}; }
//                ^^ here                             ^^ and here

and then you should call make_wrap4 like a function, i.e. not with an initializer list.


A little sidenote: you don't have three classes, you have one class and two class templates. It's also not a template class, as the comment states for wrap4.

  • wrap4 is a class template.
  • wrap4<int> and wrap4<Parameter> are classes, which you get by instantiating the class template. Some people would call such classes template class as well.

Upvotes: 1

Related Questions