一个指针传递给一个成员函数作为模板参数。为什么这项工作? [英] Passing a pointer to a member function as a template argument. Why does this work?

查看:181
本文介绍了一个指针传递给一个成员函数作为模板参数。为什么这项工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些code 100%作品的使用情况下,我有。我只是想知道如果任何人都可以解释如何以及为什么它的工作原理。

I have some code that 100% works for the use case I have. I'm just wondering if anyone can explain how and why it works.

我有一些code,处理线程和网络通信和图书馆用户传递从服务器到用户接收到的数据之间坐着一个模板类。

I have a template class that sits between some code that handles threading and network communication and the library user to pass data received from the server to the user.

template <class Bar,
          class Baz,
          class BazReturnType,
          void (Bar::*BarSetterFunction)(const BazReturnType &),
          BazReturnType (Baz::*BazGetterFunction)(void) const>
class Foo
{
    Foo( Bar *bar )
        : m_bar(bar)
    {
    }

    void FooMemberFunction( const Baz *baz )
    {
        boost::bind( BarSetterFunction, m_bar,
                     boost::bind( BazGetterFunction, baz )() ) ();
    }

    Bar *m_bar;
};

此模板实例和库根据使用的类型栏和巴兹像这样的:

This template is instantiated and used in the library depending on the types of Bar and Baz like so:

typedef Foo<MyBar,
            MyBaz,
            ReturnTypeFromBazGetterFunction,
            &MyBar::ActualSetterFunction,
            &MyBaz::ActualGetterFunction >
    MyFoo;

MyBar *bar = new MyBar;
MyBaz *baz = new MyBaz;
MyFoo *f = new MyFoo( bar );
f->FooMemberFunction( baz );

这所有的作品和boost ::绑定调用的getter / setter函数来绕过它需要去的数据。 如何和为什么传递指针到成员用作模板参数像在这种情况下工作?

This all works and boost::bind calls the getter/setter functions to pass the data around where it needs to go. How and why does passing pointers to member functions as a template argument like in this case work?


在回应的意见,我没有意识到,指针成员函数是有效的模板参数。这不是我在野外见过。我想它和它的工作,但我不是很期待。

In response to comments, I hadn't realized that pointers to member functions were valid template arguments. It's not something I had seen "in the wild" before. I tried it and it worked, but I wasn't expecting it to.

推荐答案

我认为这是一个更好的解释为什么它是可以这样做比,因为标准是这样说的

I think there is a better explanation why it is possible to do so than "because the standard says so":

它的工作原理的原因是因为指针到成员都是在编译时(指针到成员的有效从类起始位置的偏移成员)已知常数的值。因此,它们可被用作模板参数,正如任何其他整数常数可以是

The reason it works is because pointers-to-members are constant values known at compile time (pointer-to-member is effectively an offset of a member from the start of a class). Thus they can be used as parameters of templates, just as any other integer constant can be.

在另一方面,正常指针没有编译时间常数,因为它们依赖于存储器布局仅存在在运行时。它们不能是模板参数。

On the other hand, normal pointers are not compile time constants, because they depend on memory layout which only exists at runtime. They cannot be template arguments.

这篇关于一个指针传递给一个成员函数作为模板参数。为什么这项工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆