重载可变模板成员函数和可变模板函数
Overloading variadic-templated member function and variadic-templated functions
是否有一种简单的方法可以用公共函数重载可变模板函数,就像这里展示的构造函数一样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_if
和std::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++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针