我在本网站上找到了以下代码,但我不能适应我的目的:
我有工厂方法来创建具有可变参数的对象,并且具有`apply'从工厂调用方法并解压缩到之前保存到ard :: tuple ...
之前的args感谢您的帮助!
#include <iostream>
#include <utility>
#include <iostream>
#include <functional>
#include <utility>
#include <tuple>
class A {
public:
A(int, int){}
};
class B : public A {
public:
B(int x, int y):A(x, y){}
};
template <class Base, class Derived>
class BaseFactory {
public:
template <class ...Args>
static Base* create(Args&&... args){
return new Derived(std::forward<Args>(args)...);
}
};
// ------------- UTILITY---------------
template<int...> struct index_tuple{};
template<int I, typename IndexTuple, typename... Types>
struct make_indexes_impl;
template<int I, int... Indexes, typename T, typename ... Types>
struct make_indexes_impl<I, index_tuple<Indexes...>, T, Types...> {
typedef typename make_indexes_impl<I + 1, index_tuple<Indexes..., I>, Types...>::type type;
};
template<int I, int... Indexes>
struct make_indexes_impl<I, index_tuple<Indexes...> > {
typedef index_tuple<Indexes...> type;
};
template<typename ... Types>
struct make_indexes : make_indexes_impl<0, index_tuple<>, Types...> {};
// ----------UNPACK TUPLE AND APPLY TO FUNCTION ---------
template<class Ret, class... Args, int... Indexes >
Ret apply_helper( Ret (*pf)(Args...), index_tuple< Indexes... >, std::tuple<Args...>&& tup){
return pf( std::forward<Args>( std::get<Indexes>(tup))... );
}
template<class Ret, class ... Args>
Ret apply(Ret (*pf)(Args...), const std::tuple<Args...>& tup){
return apply_helper(pf, typename make_indexes<Args...>::type(), std::tuple<Args...>(tup));
}
template<class Ret, class ... Args>
Ret apply(Ret (*pf)(Args...), std::tuple<Args...>&& tup){
return apply_helper(pf, typename make_indexes<Args...>::type(), std::forward<std::tuple<Args...>>(tup));
}
int main(){
// I got error: apply(<unresolved overloaded function type>, std::tuple<int, int>)
A* = apply(&BaseFactory<A, B>::create<int,int>, std::make_tuple(5, 25));
return 0;
}
...是的,我确实从编译器中读取了输出,但是如何才能获得代码的工作版本?
答案 0 :(得分:1)
apply
的功能类型不正确。它应该是Args&&...
(就像您在BaseFactory
中所拥有的那样)而不是Args...
:
template<class Ret, class... Args, int... Indexes >
Ret apply_helper( Ret (*pf)(Args&&...), index_tuple< Indexes... >, std::tuple<Args...>&& tup){
// ^^
return pf( std::forward<Args>( std::get<Indexes>(tup))... );
}
template<class Ret, class ... Args>
Ret apply(Ret (*pf)(Args&&...), const std::tuple<Args...>& tup){
// ^^
return apply_helper(pf, typename make_indexes<Args...>::type(), std::tuple<Args...>(tup));
}
template<class Ret, class ... Args>
Ret apply(Ret (*pf)(Args&&...), std::tuple<Args...>&& tup){
// ^^
return apply_helper(pf, typename make_indexes<Args...>::type(), std::forward<std::tuple<Args...>>(tup));
}
int main(){
A* a = apply(&BaseFactory<A, B>::create<int,int>, std::make_tuple(5, 25));
return 0;
}