c++ - Visual Studio 2017 在 extern "C"中使用模板时出现不正确的错误

标签 c++ visual-studio

考虑以下代码:

#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" block 中定义 模板时出现的,显然这里不是这种情况。

似乎是 visual studio 的错误...我说得对吗?

有任何已知的解决方法吗?

最佳答案

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

#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

关于c++ - Visual Studio 2017 在 extern "C"中使用模板时出现不正确的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48910728/

相关文章:

visual-studio - 如何更改 F# 交互式 shell 的颜色

visual-studio-2010 - 在管理员(提升)模式下使用 Visual Studio 2010

c# - 在 visual studio 解决方案资源管理器中隐藏具有某些扩展名 (dll) 的文件

c++ - 如何判断两个指针是否指向同一 block 内存

c++ - 有没有办法在不破坏窗口/上下文的情况下切换全屏?

c# - DateTime 格式注释不适用于 Visual Studio 中的 Vue 应用程序

visual-studio - 为什么我不应该使用/optimize 开关来编译我的 C# 代码?

c++ - 从字符串中删除 BBcode

c++ - 在函数之间共享变量 - rand() srand

c++ - 错误 C2065 : 'MIIM_STRING' : undeclared identifier