简体   繁体   中英

Referring to templated function in template

I would like to be able to name to a templated function in a template.

Since one can name a templated class using the "template template" syntax, and since one can name a function using the "function pointer" syntax, I was wondering whether there is a syntax (or a proposal) to name a function in a template without specifying to templates.

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

One possible work-around for anyone interested in this functionality to first wrap the function D in a struct with a call method named (for example) "method", pass the struct into E as a "template template" parameter, and then call "method" in E.

The reason that I don't like this approach is that it requires a wrapper structure for every variadic function that might be used in this way.

Unfortunately, you cannot pass function templates as template parameters. The closest you can get is by using generic functors:

#include <iostream>

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

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

If you don't have C++14 generic lambdas, you can write your own functors by hand:

#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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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