【问题标题】:C++ template type deduction from arguments of a function pointer从函数指针的参数推导 C++ 模板类型
【发布时间】:2016-12-16 04:24:25
【问题描述】:

我有一个看起来像这样的模板:

template< typename T, void (*f)( T& param )>
class SomeAction
{
...
};

f用在SomeAction里面(其实f是类成员,不过我觉得没关系)。

问题是:可以通过从模板参数列表中删除 'typename T' 并让编译器推断该类型来改进吗?

谢谢!

【问题讨论】:

  • 类似的东西在 C++17 中是可能的。
  • 模板实参推导只发生在C++14模板函数调用中。你必须在模板类实例化中指定模板参数,即使它是非类型参数
  • "实际上f 是一个类成员" 正如你所展示的,f 是一个模板参数——它怎么可能也是一个类成员?
  • f 是一个标识符。它怎么可能也是一个模板参数。

标签: c++ templates c++17 type-deduction class-template


【解决方案1】:

也许您正在寻找的 C++17 功能是 Declaring non-type template parameters with auto

我还不能对此进行测试,因为还没有支持此功能的编译器,但大概它允许您编写 SomeAction 的部分特化,从而推导出 T

template<auto> class SomeAction;
template<void (*f)(auto&)> class SomeAction<f> {};

void foo(int&) { /* bla */ }

int main()
{
    // C++17 only, no compiler support yet
    SomeAction<f> s; // T deduced to be int
}

【讨论】:

  • 我认为template<auto> 更相关。
  • @cpplearner:我看不出怎么做,因为你不能把它粘在一个类型中。
  • AFAIK 在 C++17 OP 的代码将被写成template&lt; auto &gt; class SomeAction; template&lt;typename T, void (*f)( T&amp; param )&gt; class SomeAction&lt;f&gt; { ... };
  • @cpplearner 已更新,仍然不能 100% 确定这是否可行,还没有办法对其进行测试
  • 我认为这是无效的。措辞说 auto 作为“的一部分和作为模板参数中参数声明的 decl-specifier-seq 的 decl-specifier 是有效的”,它在函数的参数类型中似乎无效(除非他们添加了 c++17 的功能,void (*f)(auto) = &amp;foobar; 在本地范围内同样无效)。如果你说auto (*f)() 似乎是有效的,因为它在f 的decl-specifier-seq 中。
猜你喜欢
  • 2021-06-22
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-22
相关资源
最近更新 更多