以下代码在 GCC 中编译良好,但在 Visual Studio 中会导致
error C2782: '
bool contains(const T &,const std::initializer_list<T2>
&)
' : template parameter 'T
' is ambiguous see declaration of 'contains
' could be 'const wchar_t *
' or 'std::wstring
'
但是,如果模板参数的顺序为
,它确实可以编译和工作 template<typename T2, typename T>
这是编译器错误吗?
#include <string>
#include <iostream>
#include <set>
#include <initializer_list>
#include <algorithm>
template<typename T, typename T2>
bool contains(T const& value, std::initializer_list<T2> const& set)
{
return std::find(std::begin(set), std::end(set), value) != std::end(set);
}
int main(void)
{
std::set<std::wstring> values = { L"bar", L"not" };
for (std::wstring val : values) {
std::wcout << "\"" << val << "\" ";
if (contains(val, { L"foo", L"bar", L"baz", L"doom" })) {
std::wcout << "found" << std::endl;
}
else {
std::wcout << "not found" << std::endl;
}
}
}
编辑:我创建了一个错误报告:https://connect.microsoft.com/VisualStudio/feedbackdetail/view/982338/template-parameter-order-matters
最佳答案
我记得 VS 有一个错误,他们会在某些情况下进行双重扣除,我认为这就是这里发生的情况。 Clang 也是双向编译的,所以由于 clang + gcc 同意,这很可能是一个 VS 错误。
关于c++ - 为什么在这个例子中模板参数的顺序对 MS C++ 编译器很重要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26060355/