重载可变模板成员函数和可变模板函数

Overloading variadic-templated member function and variadic-templated functions

本文关键字:函数 成员 重载      更新时间:2023-10-16

是否有一种简单的方法可以用公共函数重载可变模板函数,就像这里展示的构造函数一样c++可变模板构造函数和公共构造函数(c++11 - c++14)

#include <iostream>
struct S {};
class C
{
  public:
  void fun(S const&) { std::cout << " fun(S const& ) " << std::endl; } // 1
  template<typename ... T>
  void fun(T&&...) { std::cout << " fun(T&&...) " << std::endl; } // 2
};
int main ()
{
    S s{};
    C c{};
    c.fun(s);
    c.fun(5); // call 1 - ?
}

我想做c.fun(5)调用非变量模板版本。对于使用std::enable_ifstd::is_constructible的施工人员,给出了类似的解决方案。我需要重载需求

我只是做了一个变通,不是很优雅

#include <iostream>
#include <type_traits>
struct S {};
class C
{
    class helper
    {
    public:
      helper(S const&) { std::cout << " fun(S const& ) " << std::endl; }
      template<typename ... T, typename = std::enable_if_t<!std::is_constructible<helper, T&&...>::value> >
      helper(T&&...) { std::cout << " fun(T&&...) " << std::endl; }
    };
  public:
  template<typename ... T>
  void fun(T&&... args) { helper { std::forward<T>(args)... }; }

};

int main ()
{
    S s{};
    C c{};
    c.fun(s);
    c.fun(5);
}