C++::使用模板技巧访问多个私有成员

C++::Access to more than one private members using templates trick

正在研究以下postaccess private member using template trick。 我想知道应该如何修改代码才能访问多个私有变量 我尝试了以下

#pragma once
template<typename Tag, typename Tag::type M>
struct Rob {
    friend typename Tag::type get( typename Tag::type) {
        return M;
    }
};
// use
struct A {
    A(int a) :a(a) { }
private:
    int a;
    int b;
};

// tag used to access A::a
template<typename Tag, typename Member>
struct TagBase {
    typedef Member type;
    friend type get(Tag);
};

struct A_f : TagBase<A_f, int A::*> { };
template struct Rob<A_f, &A::a>;
template struct Rob<A_f, &A::b>;

int main() {
   A a(42);
   std::cout << "proof: " << a.*get(A_f()) << std::endl;
}

但是我得到以下错误

error C2084: function 'int A::* Rob<A_f,pointer-to-member(0x0)>::get(int A::* )' already has a body
 message : see previous definition of 'get'
 message : see reference to class template instantiation 'Rob<A_f,pointer-to-member(0x4)>' being compiled

这是 link 演示

这是因为typename Tag::type都是int A::*,所以两个实例化定义了相同的函数

要解决此问题,您需要稍微更改示例以使其使用多种标记类型:

#include <iostream>
 
template<typename Tag, typename Tag::type M>
struct Rob {
    // Here we receive tag directly
    friend typename Tag::type get(Tag) {
        return M;
    }
};
 
// use
struct A {
    A(int a) :a(a) { }
private:
    int a;
    int b;
};
 
// tag used to access A::a
template<typename Tag, typename Member>
struct TagBase {
    typedef Member type;
    friend type get(Tag);
};
 
struct A_af : TagBase<A_af, int A::*> { };
struct A_bf : TagBase<A_bf, int A::*> { };
 
template struct Rob<A_af, &A::a>;
template struct Rob<A_bf, &A::b>;
 
int main() {
    A a(42);
    std::cout << "proof: " << a.*get(A_bf()) << a.*get(A_af()) << std::endl;
}