加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 参考模板中的模板化函数

发布时间:2020-12-16 06:51:24 所属栏目:百科 来源:网络整理
导读:我希望能够在模板中命名为模板化函数. 因为可以使用“模板模板”语法命名模板化类,并且因为可以使用“函数指针”语法命名函数,所以我想知道是否存在在模板中命名函数的语法(或提议)没有指定模板. templatetypename t_typestruct A { t_type value;};template
我希望能够在模板中命名为模板化函数.

因为可以使用“模板模板”语法命名模板化类,并且因为可以使用“函数指针”语法命名函数,所以我想知道是否存在在模板中命名函数的语法(或提议)没有指定模板.

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

对于对此功能感兴趣的任何人,可以首先使用名为(例如)“method”的调用方法将结构中的函数D包装起来,将结构作为“模板模板”参数传递给E,然后调用“方法“在E.

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

解决方法

遗憾的是,您无法将函数模板作为模板参数传递.最接近的是使用通用仿函数:

#include <iostream>

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

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

如果你没有C 14通用lambdas,你可以手工编写自己的仿函数:

#include <iostream>

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读