首页 > 解决方案 > __declspec(dllexport) 强制错误的模板覆盖编译错误

问题描述

在创建模板类的子类时,我注意到重载函数出现错误。此编译器错误是正确的,因为其中一个重载使用了副本并且类型不可复制。但是,我没有使用该功能(正确的重载与否)。所以我很惊讶得到这个错误

在搜索了一下并在godbolt中重现之后,罪魁祸首似乎是__declspec(dllexport)。
神螺栓中的复制

删除 declspec 似乎会导致正确的编译。Godbolt中的代码:

#include <memory>
#include <vector>

using namespace std;

template<class V>
struct Foo{


    void update(const V& v);
    void update(V&& v);

    std::vector<V> values;
};

template<class V>
void Foo<V>::update(const V& v)
{
    values[0] = v;
}

template<class V>
void Foo<V>::update(V&& v)
{
    values[0] = std::move(v);
}

struct __declspec(dllexport) Bar : public Foo<std::unique_ptr<int>>
{

};

int main() 
{    
    Bar f;
    
    auto i = std::make_unique<int>(5);
    //f.update(i);
    //f.update(std::move(i));
}

我的问题主要是, declspec 是如何导致这种行为的?而且,在模板类或派生类中有什么可以做的吗?

错误日志:

(19): 错误 C2280: 'std::unique_ptr> &std::unique_ptr>::operator =(const std::unique_ptr> &)': 试图用 [_Ty=int] C:/data/ 引用已删除的函数msvc/14.16.27023.1/include\memory(2338):注意:请参见 'std::unique_ptr>::operator =' 的声明,其中 [_Ty=int] C:/data/msvc/14.16.27023.1/include\memory( 2338): 注意: 'std::unique_ptr> &std::unique_ptr>::operator =(const std::unique_ptr> &)': 用 [_Ty=int] (18) 显式删除函数: 注意: 在编译类时带有 [ _Ty=int, V=std:: 的模板成员函数 'void Foo>>::update(const V &)'unique_ptr> ] (29): 注意:参见使用 [ _Ty=int ] 编译的类模板实例化 'Foo>>' 的参考

标签: c++visual-c++visual-studio-2017c++14

解决方案


推荐阅读