为什么在本例中,模板参数的顺序对MS C++编译器很重要

Why does the order of template parameters matter to the MS C++ compiler in this example?

本文关键字:MS 顺序 C++ 编译器 参数 为什么      更新时间:2023-10-16

以下代码在GCC中编译良好,但在Visual Studio中会导致

错误C2782:'bool contains(const T &,const std::initializer_list<T2>"&)":模板参数"T"不明确,请参阅的声明"contains"可以是"const wchar_t *"或"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错误。

我也遇到过类似的问题,通过切换到最新的VS Pro版本解决了这个问题。我认为这个错误在最新的VS pro版本中得到了解决,因为我记得在某个时候在更改日志中看到过它。