当模板成员函数有多个参数时,只传递第一个参数就足够了吗?

时间:2016-01-07 09:54:01

标签: c++

我正在阅读Mesos代码,并遇到以下函数调用:

install<SlaveRegisteredMessage>(
  &Slave::registered,
  &SlaveRegisteredMessage::slave_id,
  &SlaveRegisteredMessage::connection);

及其对应的模板成员函数是:

template <typename T>
class ProtobufProcess : public process::Process<T>
{
    ......
    template <typename M,
              typename P1, typename P1C,
              typename P2, typename P2C>
    void install(
      void (T::*method)(const process::UPID&, P1C, P2C),
      P1 (M::*p1)() const,
      P2 (M::*p2)() const)
    {
        ......
    }
    ......
}

因此,只传递第一个参数就足够了,不需要使用以下格式:

install<SlaveRegisteredMessage, SlaveID, SlaveID, MasterSlaveConnection, MasterSlaveConnection>(...);

1 个答案:

答案 0 :(得分:1)

所有模板参数都是可扣除的,因此您无需指定那些模板参数。

所以:

install(...);

在大多数情况下都足够了。

如果你有一个参数的重载和

void (T::*method)(const process::UPID&, P1C, P2C)

你必须以某种方式帮助编译器:

  • 提供模板参数(直到提供所有这些模板参数)
  • 指定要选择的重载(static_cast<void (T::*)(const process::UPID&, int, char)>(&T::foo))。