为什么 c++ 不为简单的嵌套类型变量推断模板参数 T?[复制]

Why c++ don't infer template argument T for simple nested types variables? [duplicate]

提问人: 提问时间:8/1/2022 更新时间:8/1/2022 访问量:85

问:

在这段代码中:

#include <iostream>
#include <vector>
#include <utility>

template <typename T>
using Separation = std::pair<std::vector<T>, std::vector<T>>;

int main()
{
    std::vector<int> vector1 = {1};

    Separation s1(vector1, vector1);

    std::cout << s1.first[0];

    return 0;
}

g++ 编译器说:error: missing template arguments before ‘(’ token

只需将 template 参数添加到 中即可解决此问题。但是,如果 v1 是整数向量,编译器难道不应该理解 T 应该是来自向量的泛型吗?Separation

C++ 类型 类型名称

评论

3赞 Kevin 8/1/2022
这是 C++20 的一项功能

答:

0赞 Aykhan Hagverdili 8/1/2022 #1

如果可以将其设置为子类型,则可以添加推导指南:

#include <iostream>
#include <vector>
#include <utility>

template <typename T>
struct Separation : std::pair<std::vector<T>, std::vector<T>> {
    using std::pair<std::vector<T>, std::vector<T>>::pair;
};

template <class T>
Separation(std::vector<T>, std::vector<T>) -> Separation<T>;

int main()
{
    std::vector<int> vector1 = {1};

    Separation s1(vector1, vector1); // works fine

    std::cout << s1.first[0];

    return 0;
}