C++ - 模板参数推导/替换失败 [英] C++ - Template argument deduction/substitution failed
问题描述
我的目标是能够在 std::vector 上使用算术运算符.考虑以下示例:
My goal is to be able to use arithmetic operators on std::vector. Consider the following example:
#include <vector>
using namespace std;
template <class S, class T, class U> vector<U> operator+(const vector<S> &a, const vector<T> &b){
vector<U> result;
result.reserve(a.size());
for(int i = 0; i < a.size();++i){
result[i] = a[i] + b[i];
}
return result;
}
int main(int argc, char** argv) {
vector<double> bla;
bla = bla + bla;
return 0;
}
此代码无法编译,因为编译器无法推导出模板参数 U(它不是 MWE,但我试图提供一个有意义的示例).为什么会这样?我知道在这里使用三个模板参数可能没有意义.我的想法是,在类型 S 和 T 都提供具有不同返回类型的匹配+"实现的情况下,我可以同时处理这两种情况.还是会出现歧义的问题?我只是想知道编译器是否应该不能推断出 U.当然,下面的代码工作正常:
This code does not compile because the compiler is not able to deduce template argument U (it's not an MWE but I tried to provide an example that makes sense). Why is this the case? I know that it might not make sense to use three template arguments here. My idea was that in the case where types S and T both provide a matching '+'-implementation with different return types, I could handle both cases at once. Or would then be a problem with ambiguity? I'm just wondering if the compiler shouldn't be able to deduce U. Of course the following code just works fine:
#include <vector>
using namespace std;
template <class S, class T> vector<S> operator+(const vector<S> &a, const vector<T> &b){
vector<S> result;
result.reserve(a.size());
for(int i = 0; i < a.size();++i){
result[i] = a[i] + b[i];
}
return result;
}
int main(int argc, char** argv) {
vector<double> bla;
bla = bla + bla;
return 0;
}
推荐答案
您可以使用 常见类型
#include <vector>
#include <type_traits>
using namespace std;
template <class S, class T>
vector<typename std::common_type<S, T>::type> operator+(const vector<S> &a, const vector<T> &b)
{
vector<typename std::common_type<S, T>::type> result;
result.reserve(a.size());
for(unsigned int i = 0; i < a.size();++i){
result[i] = a[i] + b[i];
}
return result;
}
int main() {
vector<double> bla;
bla = bla + bla;
return 0;
}
正如 Jarod42 建议的那样,您还可以使用 vector
作为另一种可能的返回类型(可能与 common_type 不同).请记住,后者需要尾随返回类型或 std::declval (C++11)
as Jarod42 suggested, you might also use vector<decltype(a[0] + b[0])>
as another possible return type (which may be different than the common_type). Keep in mind that this latter one requires trailing return type or std::declval (C++11)
这篇关于C++ - 模板参数推导/替换失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!