我有这样的情况:
#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/