仅在函数支持传递适当的可变参数时编译

问题描述 投票:0回答:1
#include <iostream>
#include <utility>

class A 
{
  public:
  void run(int value)
  {
      std::cout << value << std::endl;
  }
};

class B 
{
  public:
  void run(int value1, int value2)
  {
      std::cout << value1 << " "
                << value2 
                << std::endl;
  }
};


template<typename T,
          typename ... Args>
void call_run(T& t, Args&& ... args)
{
    // scope below should compile only
    // if T has a run function and 
    // this run function has a signature 
    // matching Args
    // (empty score otherwise)
    {
        t.run(std::forward<Args>(args)...);
    }

}


int main()
{

    int value = 1;

    A a;
    call_run(a,value);

    // compilation error if uncommented
    //B b;
    //call_run(b,value);

    return 0;
}

上面的代码可以编译并正常运行。但是,如果未注释使用B的实例调用call_run的最新部分,则由于明显的原因,代码无法编译:

main.cpp:34:9: error: no matching function for call to ‘B::run(int&)’
     t.run(std::forward<Args>(args)...);

是否可以忽略不适用的范围进行编译? (忽略此处意味着在编译时用空作用域替换有缺陷的作用域)

c++ templates variadic-functions typetraits
1个回答
4
投票

自c ++ 17起,您可以使用if constexpr

if constexpr (std::is_invocable_v<decltype(&T::run),T*,Args...>)
{
    t.run(std::forward<Args>(args)...);
}

invocable在编译时进行检查,如果返回false,则忽略[[if范围的正文。

Live demo
© www.soinside.com 2019 - 2024. All rights reserved.