从函数指针的实参中演绎出c++模板类型

C++ template type deduction from arguments of a function pointer

本文关键字:c++ 类型 演绎出 函数 指针 实参      更新时间:2023-10-16

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

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

fSomeAction内部使用(实际上f是一个类成员,但我认为这无关紧要)。

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

谢谢!

也许您正在寻找的c++ 17特性是使用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
}