如何使模板参数 [英] How to make template parameter

查看:144
本文介绍了如何使模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个采用任何类型的函数指针的元函数?在下面的代码中,如何摆脱decltype(& f)?

  template< class FuncType, FuncType functionPointer> 
void runFunc()
{
functionPointer();
}

runFunc< decltype(& f),f>();

我不想单独指定f的类型;信息已经在f中。我不喜欢诉诸定义来解决这个问题。
这基本上是应用于元编程的模板函数类型习语;我不想知道f的类型,但是无论我得到什么显然允许我调用operator()它。



我尝试过: / p>

模板参数的顺序不同;因为以后的参数似乎是可以猜到的,当你有一个函数;不可能,因为你需要转发声明FuncType,为了使它作为functionPointer的类型



切换它,让你指定returntype和参数,并给一个该类型的函数指针;不能在中间实例化具有可变模板参数的模板;如下:

  template< class ReturnType,class ... ArgTypes,ReturnType(* functionPointer)(ArgTypes .. 。) 
void runFunc()
{
functionPointer();
}

runFunc< void,int,f>(); // error; argTypes的无效模板参数,预期类型

github上还有一些上下文: https://github.com/TamaHobbit/FuncTest/blob/master/FuncTest/FuncTest .cpp

解决方案

现在很遗憾没有好的办法。



但是,标准委员会接受了一个提出有效代码的建议:

  template< ; auto functionPointer> 
void runFunc(){
functionPointer();
}

编译器支持即将推出。


How do I create a metafunction that takes any kind of function pointer? In the code below, how do I get rid of "decltype(&f)" ?

template <class FuncType, FuncType functionPointer>
void runFunc()
{
    functionPointer();
}

runFunc<decltype(&f),f>();

I don't want to have to specify the type of f seperately; the information is already there in f. I'd prefer not to resort to defines to solve this. This is basically the templated function type idiom applied to meta-programming; I don't want to know the type of f, but whatever I get in apparently allows me to call operator() on it.

Stuff I've tried:

Different order for the template parameters; since later parameters seem to be guessable when you have a function; not possible because then you would need to forward declare FuncType, in order to have it as the type for functionPointer

Switching it around so that you specify returntype and parameters and give a function pointer of that type; cannot instantiate a template with variable template arguments in the middle; that looks like below:

template <class ReturnType, class ... ArgTypes, ReturnType (*functionPointer)(ArgTypes...)>
void runFunc()
{
    functionPointer();
}

runFunc<void, int, f>(); // error; invalid template argument for 'ArgTypes', type expected

There's a bit more context here on github: https://github.com/TamaHobbit/FuncTest/blob/master/FuncTest/FuncTest.cpp

解决方案

Right now there is unfortunately no good way of doing this.

The standard committee has, however, accepted a proposal that makes this valid code:

template <auto functionPointer>
void runFunc() {
  functionPointer();
}

Compiler support should be coming soon.

这篇关于如何使模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆