【发布时间】:2019-09-18 11:02:18
【问题描述】:
我想达到什么目的:
我有以下类 Request 它有它自己的模板化功能。我想用两种状态来称呼它:
1) 提供参数;
2)只有一个参数,其他的应该被默认创建
template <typename TCmd> class Request{
public:
Request(TCmd applyingCommand): cmd(applyingCommand){}
template<typename ...TReplyData> void onSuccess(TReplyData... args){
// cmd(true, args...);
}
void onFail(){
// cmd(false) //here I want to create a wrapper, who calls the cmd with false + empty arguments
//which should be created by their constructor.
}
TCmd cmd;
};
我想如何使用它:
auto lambda = [](bool isSucceed, int v, std::vector<uint> vec){
//doing smth
qDebug() << "insideLamda" << isSucceed << v << vec;
};
std::function<void(bool, int, std::vector<uint>)> fu = lambda;
Request req(fu);
req.onSuccess(4, std::vector<uint>{1,2});
req.onFail();
所以这是我的想法如何实现它,但我坚持使用元组和可变参数模板 重点在于创建以下函数包装器
template <typename ...Args> class CmdFu
{
public:
explicit CmdFu(std::function<void(Args...)> f): m_function(f){
}
template <typename ...ProvidedArgs>void call(ProvidedArgs... args){
m_function(args...);
}
template <typename ...ProvidedArgs>void callWithDefault(ProvidedArgs...args){ //here
auto neededIndecies = std::make_index_sequence<sizeof... (Args)>{};
size_t sizeOfRemainingIndecies = sizeof... (Args) - sizeof... (args);
callDefault(neededIndecies, args...);
}
private:
template<class T> T create(){
T t; return t;
}
template <typename ...ProvidedArgs, size_t...indecies> void callDefault( std::index_sequence<indecies...>, ProvidedArgs...args){
auto providedTuple = std::make_tuple(args...);
auto providedIndecies = std::index_sequence_for<ProvidedArgs...>();
//Approach #1: I create whole default tuple and somehow applying my provided Tuple to it
// NeededTuple t;
// ResultTuple r??
// std::apply(m_function, r);
//Aprroach #2: I make std::index_sequence with remaining indexes, like 2,3,4,5 and create remaining tuple
//then make the resulting tuple with std::tuple_cat
// also std::apply
}
size_t sizeOfNeededIndecies;
std::function<void(Args...)> m_function;
using NeededTuple = std::tuple<Args...>;
};
这是我的主要问题:
1) 如何将我自己的参数设置为默认元组?
2) 如何创建以 sizeOfRemainingIndecies 为起始的 index_sequence ?
3) 是否可以检查调用签名以避免 call() 中的运行时崩溃?
【问题讨论】:
标签: c++ c++17 variadic-templates stdtuple