c++ - 扣除其他类型所依赖的类型

标签 c++ templates

我有这样的情况:

#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 两次?

我尝试了以下方法,但没有成功:

#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 不只有一个模板参数。它还有一个分配器类型的参数。要解决这个问题,您可以添加另一个模板参数,或者只使用可变参数模板模板参数,例如

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: Matching of template template-arguments excludes compatible templates他们放宽了规则并且

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

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

关于c++ - 扣除其他类型所依赖的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56225053/

相关文章:

c++ - 在表达式模板中需要非常量表达式类

html - 如何在golang中使用html

c++ - 二进制搜索到实数函数的上限

c++ - 冲浪特征提取

c++ - 错误 : no matching function for call to

C++11/模板 : Select the correct overloading of a function

python - 没有模型的 Django.contrib.flatpages

c++ - 如何将模板函数作为模板类参数传递?

android - cocos2d-x 运行一个lua脚本两次

c++ - 访客模式添加新功能