【发布时间】:2018-04-06 23:54:38
【问题描述】:
我正在研究一个应该(因为它的硬件)由可变参数模板解决的问题。我缺乏理解使我无法解决以下错误。
代码是:
#include <sstream>
#include <iostream>
#include <string>
#include <vector>
#include <tuple>
template<typename ... TL>
class LazySplitResult
{
public:
LazySplitResult(TL ...pl) :storedParams(pl ...) { }
void doStuff()
{
// invoke method with inside parameters
useStoredTuple(storedParams, std::index_sequence_for<TL...>());
}
template<typename T, typename T1, typename... Targs>
void doInsideLogic(T&& value1, Targs&& ... Fargs)
{
// there is some logic
// for example this
std::stringstream convert("0");
// it works for string,double,int ... other types are not supported
// so exception would be in place
convert >> value1;
}
void doInsideLogic()
{
}
private:
template<std::size_t... Is>
void useStoredTuple(const std::tuple<TL ...>& tuple,std::index_sequence<Is...>) {
wrapInsideLogic(std::get<Is>(tuple) ...);
}
void wrapInsideLogic(TL && ... args)
{
doInsideLogic(args...);
}
std::tuple<TL ...> storedParams;
};
template<typename ...TL>
LazySplitResult<TL ...> getResult(TL && ...pl)
{
return LazySplitResult<TL...>(pl ...);
}
int main()
{
std::string x;
int y;
double z;
// prepares an object
auto lazyResult=getResult(x, '.', '-', y, 'x', z , 'a');
// let it do its thing and set unset variables
lazyResult.doStuff();
std::cout << "x = " << x << ", y = " << y << ", z = " << z << std::endl;
return 0;
}
错误信息在这里
error C2664: 'void LazySplitResult<std::string &,char,char,int &,char,double &,char>::wrapInsideLogic(std::string &,char &&,char &&,int &,char &&,double &,char &&)': cannot convert argument 2 from 'const char' to 'char &&'
source_file.cpp(40): note: Conversion loses qualifiers
source_file.cpp(18): note: see reference to function template instantiation 'void LazySplitResult<std::string &,char,char,int &,char,double &,char>::useStoredTuple<0,1,2,3,4,5,6>(const std::tuple<std::string &,char,char,int &,char,double &,char> &,std::integer_sequence<_Ty,0,1,2,3,4,5,6>)'
复制自rextester here。
HW 的主要部分是解析公式并将结果保存在变量中,如下所示:
// declare variables and initialize class with formula
parse(x, '.', '-', y, 'x', z , 'a');
std::cout << "x = " << x << ", y = " << y << ", z = " << z << std::endl;
代码的作用相同,只是它以惰性方式执行,因此需要将参数存储在元组中以供以后使用。
我尝试实现相同的逻辑,除了懒惰,没有成功地使用元组和类。可以观察here。没有引发错误描述转换错误。
你能帮帮我吗?我完全迷路了。入口方法调用相同,处理参数的可变参数模板方法具有相同的参数......唯一的区别似乎是元组和类之间。
【问题讨论】:
-
您没有向我们提供相关代码:大概,
x、y或z是 const-qualified(或其他限定符),因此不能在不丢失限定符的情况下调用.
标签: c++ templates variadic-templates implicit-conversion stdtuple