C++ 重载可变模板成员函数和可变模板函数
有没有一种简单的方法可以用一个公共函数重载可变模板函数,如这里为构造函数所示(c++11-c++14)C++ 重载可变模板成员函数和可变模板函数,c++,templates,c++11,overloading,variadic-templates,C++,Templates,C++11,Overloading,Variadic Templates,有没有一种简单的方法可以用一个公共函数重载可变模板函数,如这里为构造函数所示(c++11-c++14) #包括 结构S{}; C类 { 公众: void fun(S const&{std::cout我只是做了一个变通,不是很优雅 #include <iostream> #include <type_traits> struct S {}; class C { class helper { public: helper(S const
#包括
结构S{};
C类
{
公众:
void fun(S const&{std::cout我只是做了一个变通,不是很优雅
#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);
}
#包括
#包括
结构S{};
C类
{
类助手
{
公众:
helper(S const&){std::cout
void fun(T&…args){helper{std::forward(args)…};}
};
int main()
{
S{};
C{};
c、 乐趣(s);;
c、 乐趣(5);
}
都为我调用了#2。它已经重载了。但是,当你调用c.fun(s)
时,参数的类型被推断为s&
。你可以用c.fun((const s&)s)
调用重载。我知道它重载了,我可以用c.fun((const s&)s)的方式调用它
,但我想像往常一样使用重载。正如构造函数所示,在变量模板化之前,可以使用std::enable_if
和std::is_constructable
轻松调用非变量模板化版本。查看链接。我也在为其他成员搜索一个好的解决方案。类似于启用变量模板化版本如果成员不是callabal,则很难获得重载函数的地址。
#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);
}