具有 const 类型或简单类型参数的方法的 C++ 模板函数

标签 c++ templates traits template-argument-deduction

假设我有两个用于调用类方法的模板函数的相同主体,如下所示:

 template <typename jsType, typename jsParamType, typename ParamPrivateType = jsParamType::PrivateType, void(PrivateType::*Method)(const ParamPrivateType&)>
    static bool SetByRefMethod(JSContext *cx, unsigned argc, JS::Value *vp)
{
...
}

 template <typename jsType, typename jsParamType, typename ParamPrivateType = jsParamType::PrivateType, void(PrivateType::*Method)(      ParamPrivateType&)>
    static bool SetByRefMethod(JSContext *cx, unsigned argc, JS::Value *vp)
{
...
}

我尝试只写一次主体,那么当被调用方法有一个参数 const 和一个参数 not< 时,让编译器使用它的正确方法是什么?/strong> const?

最佳答案

您不需要对所有这些类型进行模板化。只有第一个会做。如果您可以使用第一个模板化类型推断出其余类型,那么您应该没问题。如果可以从第一个模板类型中推导出私有(private)类型,则不需要模板中的私有(private)类型。看看下面的代码

#include <iostream>
using std::cout;
using std::endl;
#include <vector>
using std::vector;

class A {
public:
    using ClassType = int;

    void print_const_integer(const int& a) {
        cout << "A's member function accepting a const ref called" << endl;
        cout << a << endl;
    }

    void print_integer(int& a) {
        cout << "A's member function accepting a ref called" << endl;
        cout << a << endl;
    }

};
class B {
public:
    using ClassType = int;

    void print_integer(int& a) {
        cout << "B's member function called" << endl;
        cout << a << endl;
    }
};

template <typename TYPE>
void function(TYPE object, void (TYPE::*member_func_pointer)(int&)) {
    typename TYPE::ClassType a = 1;
    (object.*member_func_pointer)(a);
}

template <typename TYPE>
void function(TYPE object, void (TYPE::*member_func_pointer)(const int&)) {
    typename TYPE::ClassType a = 1;
    (object.*member_func_pointer)(a);
}

int main() {
    A a;
    B b;

    function(a, &A::print_const_integer);
    function(a, &A::print_integer);
    function(b, &B::print_integer);

    return 0;
}

希望对您有所帮助!

关于具有 const 类型或简单类型参数的方法的 C++ 模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35234425/

相关文章:

c# - 使用 PInvoke 将 void 传递给 void

C++无重复数随机数生成器

c++ - 对参数使用模板语法

c++ - 错误 C2955 : use of class template requires template argument list

c++ - 类具有相同的接口(interface),但参数类型不同

rust - 为什么编译器会导致 “cycle detected when processing …”错误?

c++ - is_functor C++ 特征类可能吗?

c++ - 删除导致段错误的 cout 语句

generics - 对于必须实现 "iter"函数的类型,我应该使用哪个特征边界

c++ - 如何从文件中读取某些字符串?在 C++ 中丢弃我不想要的那些