显式实例化失败的原因是什么

What would be the reason that the explicit instantiation failed?

本文关键字:是什么 失败 实例化      更新时间:2023-10-16
/* MyClass.h */
class MyClass
{
public:
    template <typename T>
    void Foo(const T &val);
};
/* MyClass.cpp */
#include <string>
#include <iostream>
#define EXPLICIT_INSTANTIATION_FOO(MyType) 
    template void MyClass::Foo(const MyType &val)
EXPLICIT_INSTANTIATION_FOO(int);
EXPLICIT_INSTANTIATION_FOO(float);
EXPLICIT_INSTANTIATION_FOO(std::string);
template <typename T>
void MyClass::Foo(const T &val)
{
    std::cout << "My Value: " << val << std::endl;
}

由于其他原因,我无法在头文件中定义 Foo,然后我尝试显式实例化源文件中我需要的所有类型。它在 g++-4.8 上运行得很好。

然后,一旦我提交了代码,我发现建筑物在Windows 10, x86_64, cl19失败了。这是一个未解决的符号错误,看起来我的实例没有从对象中暴露出来。

但有趣的是,当我尝试通过制作上面的简单片段在我自己的 Windows 上重现此错误时。我发现它在我的 vs2017 上使用 cl19 运行良好......

公司和个人机器之间会有数千种配置不同,但我只是不知道实例化在那里不起作用的原因是什么......任何想法表示赞赏!:)

补充:

仅供参考,完整的代码在这里:

/* MyClass.h */
#pragma once
class MyClass
{
public:
    MyClass();
    ~MyClass();
    template <typename T>
    void Foo(const T &val);
};
/* MyClass.cpp */
#include "MyClass.h"
#include <iostream>
#include <string>
#define EXPLICIT_INSTANTIATION_FOO(MyType) 
    template void MyClass::Foo(const MyType &val)
EXPLICIT_INSTANTIATION_FOO(int);
EXPLICIT_INSTANTIATION_FOO(float);
EXPLICIT_INSTANTIATION_FOO(std::string);
MyClass::MyClass() {}
MyClass::~MyClass() {}
template <typename T>
void MyClass::Foo(const T &val)
{
    std::cout << "My Value: " << val << std::endl;
}
/* main.cpp */
#include "MyClass.h"
#include <iostream>
#include <string>
int main()
{
    std::string v = "hello";
    MyClass cls;
    cls.Foo(v);
    std::cin.get();
    return 0;
}

这通过了 msvc 上的编译。

将函数定义移动到EXPLICIT_INSTANTIATION_FOO调用之前。这是永远不应该工作的东西,但编译器,他们正在慢慢地解决这个问题。如果你想让 msvc 拒绝它,请使用/permissive- 标志。

谢谢大家,这个愚蠢的问题解决了。

原因是模板实例化不会从 Windows 上的模板定义继承 dllexport 属性。显然,它适用于我愚蠢的测试代码,因为它没有编译为 DLL :)