【问题标题】:How to have a variable number of arguments, of unknown determined type?如何拥有可变数量的未知确定类型的参数?
【发布时间】:2020-04-14 15:07:26
【问题描述】:

我真的不知道正确的标题是什么,所以请原谅我写的。我认为最好举个例子。

void foo(std::pair<std::string, T>, std::pair<std::string, U>, std::pair<std::string, Z>, ...);

其中 T、U 和 Z 可以是多种类型,但列表中的参数数量是可变的。我知道您可以使用参数包并假设它们沿这条线传递对象,但是当您调用该函数时,您不能调用对聚合初始值设定项。

template<typename ...args>
void foo(args... values);
//the following isn't allowed, cause it doesn't know the type. (this is what I want it to look like)
foo({"hi",5}, {"hello", true});

有没有可能我正在尝试做的事情?任何帮助将不胜感激。

【问题讨论】:

    标签: c++ templates variadic-templates template-meta-programming


    【解决方案1】:

    从 C++17 开始,您可以利用 CTAD (Class Template Argument Deduction) 并使用 std::stringoperator""s 来拥有

    template<typename ...args>
    void foo(args... values) {}
    // or to make sure pair types are provided
    //template<typename ...args>
    //void foo(std::pair<std::string, args>... values) {}
    
    int main()
    {
        using std::pair;
        using namespace std::string_literals;
    
        foo(pair{"hi"s, 5}, pair{"hello"s, true});
    }
    

    【讨论】:

    • 没有对{...}有什么办法吗?
    • @JosephGrimaldo 不幸的是,没有。 {stuff} 没有类型,所以 foo({stuff}) 永远无法推断出类型。这意味着如果你想要一个可变参数模板,你必须指定每个{} 的类型。否则,您将不得不按照老派的方式进行操作并提供 N 个重载,其中每个重载比最后一个重载多了一个参数。
    【解决方案2】:

    您可以对成对的约束参数执行以下操作:

    template<typename ...Ts>
    void foo(std::pair<std::string, Ts>... values);
    

    调用必须类似于:

    foo(std::pair{std::string("hi"),5}, std::pair{std::string("hello"), true});
    foo<int, bool>({"hi",5}, {"hello", true});
    

    {"hi",5} 没有类型,所以不能推断模板类型。 在这种情况下,您必须提供模板参数。

    如果您提供正确的配对(std::pair&lt;std::string, T&gt;,而不是 std::pair&lt;const char*, T&gt;),则可以进行扣除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-08
      • 2018-01-26
      • 2011-05-20
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      相关资源
      最近更新 更多