加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – Variadic模板功能解压缩顺序

发布时间:2020-12-16 10:01:32 所属栏目:百科 来源:网络整理
导读:我有这个代码: templatetypename ...Tstruct Test{ void call(string str) { abc(getT(str)...); } templatetypename U string get(string inp) { string ret{ inp[0] }; inp.erase(0,1); cout ret endl; // first "a",next "b",next "c" - everything is o
我有这个代码:

template<typename ...T>
struct Test
{
    void call(string str)
    {
        abc(get<T>(str)...);
    }

    template<typename U>
    string get(string& inp)
    {
        string ret{ inp[0] };
        inp.erase(0,1);

        cout << ret << endl; // first "a",next "b",next "c" - everything is ok

        return ret;
    }

    void abc(string a,string b,string c)
    {
        cout << a << " " << b << " " << c << endl; // "b c a" - why?
    }
};

我这样称呼它:

Test<int,bool,float> test;
test.call("abc");

输出结果是b c a think a expect a b c.而且在get()函数中我有一个正确的顺序.为什么是这样?我找不到关于这个订单的任何规则.

解决方法

函数参数的评估顺序未指定.

abc(get<T>(str)...);

这基本上与:

abc(get<T1>(str),get<T2>(str),get<TN>(str));

您可以通过生成用于存储字符串的数组,然后从该数组调度来强制执行评估顺序:

template <std::size_t N,std::size_t... Idx>
void call_helper(std::array<std::string,N> arr,std::index_sequence<Idx...>) {
    abc(std::get<Idx>(arr)...);
}

void call(string str)
{
    std::array<std::string,sizeof...(T)> arr { get<T>(str)... }; 
    call_helper(arr,std::index_sequence_for<T...>{});
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读