显式实例化失败的原因是什么
What would be the reason that the explicit instantiation failed?
/* 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 :)
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- C++避免重复声明的语法是什么
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- C++从另一个类访问公共静态向量的正确方法是什么
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- C++中名称篡改的目的是什么
- 在 c++ 中拥有一组结构的正确方法是什么?
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 派生类销毁的最佳实践是什么
- 这个语法std::class<>{}(arg1, arg2) 在C++中是什么意思?
- 访问提升:shared_ptr 主范围外崩溃,断言失败:px != 0.指针的正确用法是什么?
- 指示 Qi 变换属性失败的适当方法是什么?
- 显式实例化失败的原因是什么
- QtDCM 编译失败的可能原因是什么?
- 错误 opencv 错误断言失败 (p [-1] <= 2) 是什么意思以及如何处理它?
- 当我尝试caputre〔this〕时,用于回调函数的lambda表达式失败,原因是什么
- 打破gdb中失败断言的正确方法是什么
- Cython c++示例失败了,原因是什么