【问题标题】:Template function overload for type containing a type包含类型的类型的模板函数重载
【发布时间】:2017-06-13 01:45:52
【问题描述】:

我正在尝试执行以下操作:

#include <iostream>
#include <vector>
#include <tuple>
#include <list>

template <typename T>
void f(T t) {
    std::cout << "1" << std::endl;
}

template <typename T, typename V>
void f(T<std::tuple<V>> t) {
    std::cout << "2" << std::endl;
}

int main() {
    f(std::list<double>{}); // should use first template
    f(std::vector<std::tuple<int>>{}); // should use second template
}

在 C++14 中最简单的方法是什么?我以为我可以通过这种方式进行模式匹配,但编译器不会有它。

【问题讨论】:

    标签: c++ templates c++14 template-templates


    【解决方案1】:

    模板参数T用作模板名称,因此应声明为template template parameter。例如

    template <template <typename...> class T, typename V>
    //        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    void f(T<std::tuple<V>> t) {
        std::cout << "2" << std::endl;
    }
    

    LIVE

    【讨论】:

    • 我检查了你的答案,它确实编译成功,但是至少在 MSVS 2017 CE 中,来自 OP 主函数的第二个问题或函数调用没有使用第二个版本的函数模板实际上使用第一个。我不知道这是否与编译器优化有关,但我认为这是需要注意的。除此之外;好答案!
    • @FrancisCugler 我用 Clang 和 GCC 试了一下,都按预期工作; VS 似乎无法推断出第二个函数模板的类型 T,我不确定,可能是错误。
    • 哦,好吧,因为我最终确实问了这个问题:stackoverflow.com/questions/44511401/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多