考虑以下代码:
#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; }
);
}
关于c++ - Visual Studio 2017 在 extern "C"中使用模板时出现不正确的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48910728/