Visual Studio 2017 在外部"C"中使用模板时出现不正确的错误

Visual Studio 2017 Improper error on template use in extern "C"

本文关键字:错误 不正确 2017 Studio 外部 Visual      更新时间:2023-10-16

考虑以下代码:

#include <vector>
#include <algorithm>
template<typename T, typename R, typename Op>
inline
std::vector<T>
transform_inline(const R & collection, Op op)
{
   std::vector<T> result;
   std::transform
   (
      std::begin(collection),
      std::end(collection),
      std::back_inserter(result),
      op
   );
   return result;
}
extern "C"
{
    void myFunc()
    {
        std::vector<std::pair<double,int>> data;
        transform_inline<double>
        (
            data,
            [](auto & o){ return o.first; }
        );
    }
}

它在GCC和Clang中编译,但是Visual Studio说:

<source>(31): error C2894: templates cannot be declared to have 'C' linkage
Microsoft (R) C/C++ Optimizing Compiler Version 19.10.25017 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.
Compiler returned: 2

请参阅:https://godbolt.org/g/vgvl4t

通常,当您定义时,该错误通常是Extern" C"块中的模板,这显然不是这样。

看起来像一个视觉工作室错误...我正确吗?

任何已知的解决方法?

我不会混合声明和定义。以下是可编译的代码。

#include <vector>
#include <algorithm>
template<typename T, typename R, typename Op>
inline
std::vector<T>
transform_inline(const R & collection, Op op)
{
   std::vector<T> result;
   std::transform
   (
      std::begin(collection),
      std::end(collection),
      std::back_inserter(result),
      op
   );
   return result;
}
extern "C"
{
    void myFunc();
}
void myFunc()
{
    std::vector<std::pair<double,int>> data;
    transform_inline<double>
    (
        data,
        [](auto & o){ return o.first; }
    );
}

请参阅:https://godbolt.org/g/pbqcfc