您可以使用调度技术通过转换排名来选择重载:
#include <memory>
#include <iostream>
template<typename T, typename... Args>
auto make_unique_impl(int, Args&&... args)
-> decltype(new T {std::forward<Args>(args)...}, std::unique_ptr<T>{}) {
std::cout << "{..} variant" << std::endl;
return std::unique_ptr<T>(new T { std::forward<Args>(args)... });
}
template<typename T, typename... Args>
auto make_unique_impl(short, Args&&... args)
-> decltype(new T (std::forward<Args>(args)...), std::unique_ptr<T>{}) {
std::cout << "(..) variant" << std::endl;
return std::unique_ptr<T>(new T ( std::forward<Args>(args)... ));
}
// dispatcher
template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return make_unique_impl<T>(0, std::forward<Args>(args)...);
}
调度程序中的调用将更喜欢int
重载,因为0
它的类型是int
. 但是如果替换失败,另一个重载也是可行的(通过积分转换)。
使用示例:
struct my_type
{
my_type(int, int) {}
my_type(std::initializer_list<int>) = delete;
};
struct my_other_type
{
my_other_type(int, int) {}
};
int main()
{
make_unique<my_type>(1, 2);
make_unique<my_other_type>(1, 2);
}