如何为此示例中的所有参数设置相同的类型? [英] How to set the same type for all arguments in this example?

查看:103
本文介绍了如何为此示例中的所有参数设置相同的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是为了练习我试图写一个可变参数模板,将一些值输入到向量。我写了以下:

Just for practice I'm trying to write a variadic template that inputs some values into vector. I wrote the following:

template <class T>
void add(vector<T> *v, T n){
    v->push_back(n);
}
template <class T, class... T2>
void add(vector<T> *v, T n, T2... rest){
    v->push_back(n);
    add(v, rest...);
}

要测试这些,我使用以下命令:

To test these I use the following:

vector<int> vI;
add(&vI, 10, 30, 25);

for (int i = 0; i < vI.size(); i++)
    cout << vI[i] << endl;

一切正常,但我想知道第二个模板是否可以写成它只使用一种类型(T或T2),因为向量(push_back)期望所有参数的相同类型?事实上,我想确保T = T2一路。

Everything works as expected, but I'm wondering if the second template could be written in a way that it uses only one type (T or T2) since vector (push_back) expects the same type for all arguments? In fact, I would like to ensure T = T2 all the way.

推荐答案

有趣的是,您当前的代码已经确保了

The funny thing is that your current code already ensures that calls like

add(&vI, 10, 10.f, 20); 

不编译。如果参数的类型与向量的值类型不同,那么它最终将成为调用中的第二个参数,如

doesn't compile. If an argument's type is different from the vector's value type, then eventually it will become the second argument in a call like

add(&vI, 10.f, 20);

然后模板参数扣除将失败,因为它推导出 / code>。

and then template argument deduction will fail because it deduces conflicting types for T.

如果要在递归中发生扣减失败时减少错误消息的可怕数量,SFINAE或 static_assert 可以帮助。我个人更喜欢Columbo的诀窍:

If you want to reduce the horrendous amount of error messages when the deduction failure happens deep in the recursion, SFINAE or static_assert can help. I personally prefer Columbo's trick:

template<bool...> class bool_pack;
template<bool...b>
using all_true = std::is_same<bool_pack<true, b...>, bool_pack<b..., true>>;

template <class T, class... T2>
void add(vector<T> *v, T n, T2... rest)
{
    static_assert(all_true<std::is_same<T, T2>{}...>{}, "T2 must be all Ts");
    v->push_back(n);
    add(v, rest...);
}

目前没有办法避免使用T和T2呼叫)。该委员会正在考虑在这方面的潜在改进,但是,一些可能会进入下一个标准。

There is currently no way to avoid using both T and T2 (without modifying the call). The committee is considering potential improvements in this area, however, so something might make its way into the next standard.

这篇关于如何为此示例中的所有参数设置相同的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆