C ++模板参数作为函数调用名称 [英] C++ template parameter as function call name

查看:78
本文介绍了C ++模板参数作为函数调用名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,可以进行如下操作:

In C++, is possible to make something like this:

class A 
{
public:
   template <typename ClassType, typename MethodName, typename ...Args>
   static func()
   {
       ClassType t = GetPtr<ClassType>();
       t->MethodName(GetArg<Args>()...);
   }
}

A::func<B, sum, double, double>(); //should call B->sum(double, double)
A::func<C, sum2, std::string, double, double>(); //should call C->sum2(std::string, double, double)

其中 GetPtr GetArgs 是从字典中获取指针的工作方法。

where GetPtr and GetArgs are working methods to obtain pointers from dictionary.

推荐答案

您可以使用非类型模板参数,例如:

You could make use of non-type template parameters like:

template <typename ClassType, typename MethodType, MethodType MethodName, typename ...Args>
static void func() {
    ClassType t = GetPtr<ClassType>();
    (t->*MethodName)(GetArg<Args>()...);
}

按以下方式使用:

A::func<B, double (B::*)(double,double), &B::sum, double, double>();

当编译器支持c ++ 17时,您的代码甚至可以缩短:

When your compiler will support c++17 your code could get even shortened:

template <typename ClassType, auto MethodName, typename ...Args>
static void func() {
    ClassType t = GetPtr<ClassType>();
    (t->*MethodName)(GetArg<Args>()...);
}

用法:

A::func<B, &B::sum, double, double>();

这篇关于C ++模板参数作为函数调用名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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