首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用模板技巧将C++::Access连接到多个私有成员

使用模板技巧将C++::Access连接到多个私有成员
EN

Stack Overflow用户
提问于 2020-12-04 23:59:58
回答 1查看 94关注 0票数 2

我正在研究下面的帖子access private member using template trick。我想知道应该如何修改代码,以便访问多个私有变量。我尝试了以下方法

代码语言:javascript
复制
#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;
}

但是我得到了以下错误

代码语言:javascript
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-12-05 00:09:32

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

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

代码语言:javascript
复制
#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;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65146769

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档