扣除其他类型依赖的类型 [英] Deduct type of which other type is dependent

查看:28
本文介绍了扣除其他类型依赖的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种情况:

#include <vector>

template<typename T, typename U = T>
U f(T data) {
    return U();
}

int main() {
    std::vector<int> vec = {1,2,3};
    return f<std::vector<int>, int>(vec);
}

T 始终是模板类型,而 U 始终是 T 所依赖的类型.有没有办法从 T 获取 U 以便在 f 调用中不显式 int 两次?

T is always a templated type and U is always the type that T depends. Is there a way to get U from T in order to don't explicit int twice in f call?

我尝试了以下方法,但没有奏效:

I've tried the following, but It didn't work:

#include <vector>

template<template<class> class T, class U>
U f(T<U> data) {
    return U();
}

int main() {
    std::vector<int> vec = {1,2,3};
    return f<std::vector, int>(vec);
}

推荐答案

这里的问题是 std::vector 不只有一个模板参数.它还具有分配器类型的参数.为了解决这个问题,您可以添加另一个模板参数,或者只使用像

The issue here is std::vector doesn't have just one template parameter. It also has a parameter for the allocator type. To get around that you can add another template parameter, or just use a variadic template template parameter like

template<template<class...> class T, class U>
U f(T<U> data) {
    return U();
}

哪个可以使用

return f<std::vector, int>(vec);

甚至更好

return f(vec);

请注意,此行为已在 C++17 中更改.使用 DR:模板模板参数的匹配排除兼容模板他们放宽了规则和

Do note that this behavior has been changed in C++17. With DR: Matching of template template-arguments excludes compatible templates they relaxed the rules and

template<template<class> class T, class U>
U f(T<U> data) {
    return U();
}

将在 C++17 模式下使用 gcc,在启用 -frelaxed-template-template-args 的情况下在 C++17 中使用 clang.

will work with gcc in C++17 mode and clang in C++17 with -frelaxed-template-template-args enabled.

这篇关于扣除其他类型依赖的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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