【问题标题】:Referring to templated function in template引用模板中的模板化函数
【发布时间】:2016-03-14 10:46:16
【问题描述】:

我希望能够命名模板中的模板函数。

由于可以使用“模板模板”语法命名模板类,并且可以使用“函数指针”语法命名函数,我想知道是否存在命名函数的语法(或建议)在模板中而不指定模板。

template<typename t_type>
struct A {
  t_type value;
};

template<template<typename> class t_type>
struct B {
  t_type<int> value;
};

template<int added>
constexpr int C (int value) {
  return value + added;
}

template<int (*function)(int)>
constexpr int D (int value) {
  return function(value);
}

// GOAL: Template argument referring to templated function
/*template<template<int> int (*function)(int)>
constexpr int E (int value) {
  return function<1>(value);
}*/

int main() {
  B<A> tt_good;
  int fp_good = D< &C<1> >(0);
  /*int fp_fail = E< &C >(0);*/

  return 0;
}

对于任何对此功能感兴趣的人来说,一种可能的解决方法是首先将函数 D 包装在一个带有名为(例如)“method”的调用方法的结构中,将该结构作为“模板模板”参数传递给 E,然后然后在 E 中调用“方法”。

我不喜欢这种方法的原因是它需要一个包装结构,用于可能以这种方式使用的每个可变参数函数。

【问题讨论】:

  • 模板模板参数只能通过类型模板,如果没有记错的话。
  • 您对E 的假设调用缺少第二个模板参数:如果可能,它将是E&lt;C, 1&gt;(0)。此时,您也可以使用D&lt;C&lt;1&gt;&gt;(0) 达到相同的效果。
  • My goal is to be able to expand a variadic into the template of a function, using a type that records the variadic. 我不明白这是什么意思。也许你应该展示一些代码来解释你真正想要实现的目标,而不是你希望能帮助你实现目标的不可行的方法。另见:XY problem
  • @IgorTandetnik 为避免混淆,我删除了“目标”声明。而且,根据您之前的评论,修改了代码,使其显示确实,如果我要完全指定模板参数,那么我将能够引用该函数...
  • @IgorTandetnik 正如在某些情况下使用“模板模板”引用模板容器类型很有用一样,在某些情况下,我无需引用模板化函数会很有帮助指定模板参数。所以,我认为我的问题的答案是“没有这样的语法”

标签: c++ c++11 template-templates


【解决方案1】:

很遗憾,您不能将函数模板作为模板参数传递。最接近的方法是使用泛型函子:

#include <iostream>

template <typename F>
void call(F f)
{
    f("hello, world\n");
}

int main()
{
    call([](auto value) { std::cout << value; });
}

如果您没有 C++14 通用 lambda,您可以手动编写自己的仿函数:

#include <iostream>

template <typename F>
void call(F f)
{
    f("hello, world\n");
}

struct print
{
    template <typename T>
    void operator()(T value) const
    {
        std::cout << value;
    }
};

int main()
{
    call(print());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2018-10-23
    • 1970-01-01
    相关资源
    最近更新 更多