Tigran Saluev
Tigran Saluev

Reputation: 3582

Partial instantiation of template template parameter

Suppose I build a class template with template parameter:

template<template<typename> class A> class B;

And now I want to make an instantiation, for example for A being functions taking int (e.g. for arguments like template<class T> void f(int)). Is there any way to do this?

Upvotes: 3

Views: 418

Answers (3)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275320

You cannot pass template functions around to other templates.

You can create template objects that act like template functions, such as:

struct my_wrapper {
  template<class T>
  static void invoke(int) {};
};

You can pass a type and expect that it have a static template function called invoke that takes a type.

Upvotes: 0

Smeeheey
Smeeheey

Reputation: 10316

As per the other answer, template template arguments cannot be used with function templates. You could however, simulate desired functionality by wrapping your function in a templated functor instead. The simplest would be an std::function. Here is a silly example to demonstrate this:

#include <iostream>
#include <functional>

template<template <class A> class T>
class B
{
public:    
    template<typename Arg>
    void invoke(T<Arg> target, Arg arg)
    {
        target(arg);
    }
};

template<typename T>
void f(T arg)
{
    std::cout << arg << std::endl;
}

template<typename T>
using fWrapper = std::function<void(T)>;

int main()
{
    B<fWrapper> b;

    b.invoke<int>(fWrapper<int>(f<int>), 1);

    return 0;
}

Upvotes: 1

songyuanyao
songyuanyao

Reputation: 172894

No. Template template arguments can't be used with function template.

A template argument for a template template parameter must be an id-expression which names a class template or a template alias.

Upvotes: 1

Related Questions