c++ - 重载可变模板成员函数和可变模板函数

标签 c++ templates c++11 overloading variadic-templates

有没有简单的方法用通用函数重载可变参数模板函数,就像此处为构造函数所示 c++ variadic template constructor and common constructors (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);

}

关于c++ - 重载可变模板成员函数和可变模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32960528/

相关文章:

c++ - 动态创建一个新数组,其中原始数组中的每个项目都被复制给定的次数

继承模板类中的 C++ 编译器错误

c++ - 从通过指针取消引用从 C 函数调用的 C++ 函数中抛出

c++ - move 构造函数可以接受类本身以外的参数吗?

c++ - string::npos 在这段代码中是什么意思?

c# - 将数据从 C++ 传递到 C# 的最有效方法

c++ - notify_all 崩溃后直接删除 std::condition_variable_any

C++ 模板 - 评估模板内的静态内联方法并将结果作为模板类型参数传递

c++ - 使用 lambda 的可变参数模板 : error with g++ but running with clang++

c++ - 如何在 Windows 上将 C++11 线程关联设置为 NUMA 节点?