c++ - 生成可以区分 ID(Foo::a()) 和 ID(Foo::b()) 的唯一标识符

标签 c++ c++11 uniqueidentifier member-functions

假设我有:

struct S{
    void f(int);
    float g(int,int);
    void h(int);
}

#define UID(w) /* how to do it? */

cout << UID(S::f);
cout << UID(S::g);
cout << UID(S::h);

我需要一些方法来为每个成员创建唯一的编号、字符串或地址。

这是因为我将要使用:

#define BIND(foo) Generate<decltype(&foo), &foo>::call

u = & BIND(S::f)
v = & BIND(S::g)
w = & BIND(S::h)

BIND 生成关联的 C 风格函数

这是生成器的草图:

template< typename F f >
struct Generate {}

template < typename R,  typename ...Arg,  R(S::*target)(Arg...) >
struct Generate< R(S::*)(Arg...),target >
{
    static R call( PyObject* self, Arg... carg)
    {
        cout << ??? // the name, e.g. 'S::b'

我需要这个函数来cout生成它的S::foo 的名称。

所以问题的后半部分是:如何从 call 中恢复相同的 UID?

我尝试创建 UID 的原因是我可以:

static std::map<void*, std::string> names_map;

然后我可以修改我的:

#define BIND(foo) Generate<decltype(&foo), &foo>::call; \
                  names_map[ UID(foo) ] = std::string(#foo);

    static R call( PyObject* self, Arg... carg)
    {
        cout << names_map[ UID(  R(S::*target)(Arg...)  ) ];

但是如何真正做到这一点呢?

我整理了一个测试用例 on coliru -- 任何人都可以让它发挥作用吗?

最佳答案

这听起来像是一个 XY 问题。您实际需要的是一种将特定类型 ( Generate<...> ) 与可用作 map 键的内容相关联的方法。有一种标准方法可以做到这一点——它叫做 std::type_index .

static std::map<std::type_index, std::string> names_map;

/* ... */

template <typename R, typename... Arg, R(Base::*target)(Arg...)>
struct Generate< R(Base::*)(Arg...), target >
{
    static void call() 
    {
        std::cout << "TARG:" << names_map[ std::type_index( typeid(Generate) ) ] << std::endl;
    }
};

#define BIND(fp, cxx_target) \
                            fp = &Generate< decltype(&cxx_target), &cxx_target >::call; \
                            names_map[ std::type_index(typeid(Generate< decltype(&cxx_target), &cxx_target >)) ] = std::string(#cxx_target);

Demo .

关于c++ - 生成可以区分 ID(Foo::a()) 和 ID(Foo::b()) 的唯一标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27913011/

相关文章:

c++ - 为什么类声明顺序仍然对原型(prototype)设计很重要?

c++ - FANN:使用从多个文件读取的数据训练 ANN 时发生内存泄漏

c++ - 如何在 GCC 5 中处理双 ABI?

具有唯一 id 作为目录的 Seo 友好 url 算作重复内容吗?

javascript - 有什么方法可以识别 JavaScript 中的浏览器选项卡?

c++ - 使用 CreateProcess 时奇怪的减速

c++ - 在其他组件上使用 QTableView 缓慢滚动

c++ - 通过模板中的成员函数指针对 shared_ptr 的成员函数调用

c++ - 使用带有 std::unique_ptr 元素的 boost::multi_index::multi_index_container 的初始化列表

angularjs - 多次使用指令时附加唯一 ID