简体   繁体   English

模板模板参数的部分实例化

[英]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 (eg for arguments like template<class T> void f(int) ). 现在我想进行一个实例化,例如AA带int的函数(例如对于template<class T> void f(int) )这样的参数。 Is there any way to do this? 有没有办法做到这一点?

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. 模板模板参数的模板参数必须是id-expression,用于命名类模板或模板别名。

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 . 最简单的是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;
}

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. 您可以传递一个类型,并期望它有一个名为invoke的静态模板函数,它接受一个类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM