有没有简单的方法用通用函数重载可变参数模板函数,就像此处为构造函数所示 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_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++ - 重载可变模板成员函数和可变模板函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32960528/