C++ 模板参数作为函数调用名称

标签 c++ c++11 templates variadic-templates

在 C++ 中,可以做这样的事情:

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)

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

最佳答案

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

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 时,您的代码甚至可以缩短:

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++ 模板参数作为函数调用名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40072627/

相关文章:

c++ - 正确别名 vector

c++ - 你使用 Qt,你为什么使用它?

c++ - 是否可以更改 ostringstream rdbuf?

c++ - 在 C++11 函数中使用尾随返回类型的优势

c++ - 通过套接字发送和接收 std::string

c++ - 为什么使用两个 sizeof 来检查一个类是否是默认可构造的,而一个却不行?

c++ - 自动统计一个TMP中实例化类的个数?

c++ - 无法更改指针矩阵的值

c++ - `std::vector< std::unique_ptr< T >>` 错误

css - 当菜单最后呈现时让博客文本环绕菜单 DIV