问题描述
Context:试图创建一个类来解包一个元组(用于存储可变参数模板参数)。受到这个答案的启发https://stackoverflow.com/a/24804339/11510510我有一些可以完成这项工作的东西。
(如果不是,我只能使用 C++11,否则我将使用 C++17 中的 std::apply)
问题:它仅在使用特定类型创建对象时才编译,而不是在模板内部。
要实例化的目标类
template<class C,class ...Args>
struct APPLY_TUPLE{};
template<class C,class ...Args>
struct APPLY_TUPLE<C,std::tuple<Args...>>{
// irrelevant code
};
实例化 APPLY_TUPPLE 的类
template<typename C,typename R>
struct TupledCall
{
TupledCall(C& obj) : object{obj} {}
R MethodTrigger(){
// instantiate APPLY_TUPLE here with type of object
}
C &object;
};
/*Instantiation as*/
auto obj = Summator();
auto tupledCall = TupledCall<Summator,int>(obj);
tupledCall.MethodTrigger();
编译什么
R MethodTrigger(){
tuple<int,int,int> list = make_tuple(1,5,4);
auto tup = APPLY_TUPLE<Summator,args(list)>(object);
return tup.delayed_call<int,&Summator::sum>(list);
}
R MethodTrigger(){
tuple<int,4);
Summator s = Summator();
auto tup = APPLY_TUPLE<typename decay<decltype(s)>::type,&Summator::sum>(list);
}
什么不能编译
R MethodTrigger(){
tuple<int,4);
auto tup = APPLY_TUPLE<C,4);
auto tup = APPLY_TUPLE<typename decay<decltype(object)>::type,4);
C sum = C(); // C should be deducted as Summator in this template
auto tup = APPLY_TUPLE<typename decay<decltype(object)>::type,&Sumator::sum>(list);
}
它们之间有什么区别?为什么在尝试使解决方案通用时无法编译?
编译器错误
<source>: In member function 'R TupledCall<C,R>::MethodTrigger()':
<source>:80:37: error: expected primary-expression before 'int'
80 | return tup.delayed_call<int,&Summator::sum>(list);
| ^~~
<source>:80:37: error: expected ';' before 'int'
<source>:80:41: error: expected unqualified-id before ',' token
80 | return tup.delayed_call<int,&Summator::sum>(list);
| ^
<source>:80:57: error: qualified-id in declaration before '>' token
80 | return tup.delayed_call<int,&Summator::sum>(list);
最小可重现示例 https://godbolt.org/z/bPYWhfM7d
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)