我很难弄清楚如何在 C# 中使父类函数可见。
假设我有一个模板类,它定义了一个函数 foo()
template <int Dim, typename Type>
public ref class FixedNP
{
public:
float foo() {return 1;};
};
然后我有一个继承自 FixedNP 模板的类:
public ref class Vector3fP : public FixedNP<3, float>
{
}
当我尝试从 C# 调用 foo() 函数时,例如。
Vector3fP bar = new Vector3fP();
bar.foo();
它说函数 Vector3fP 不包含 foo 的定义。
当我将 foo() 的定义移动到 Vector3fP 类时,它工作正常。然而,这在实际代码中是不可行的,因为 FixedNP 模板包含相当多的函数,这些函数应该从大约 4 个不同的类继承。
在网上搜索了一下,发现添加了
using FixedNP<3, float>::foo;
Vector3fP 为某人解决了类似的问题。然而,在我的例子中,它只会导致另一个错误,这次是在编译 C++/CLI 代码时:
error C3182: 'Vector3fP' : a member using-declaration or access declaration is illegal within a managed type
关于如何使我的函数在 C# 中可见的任何建议?
最佳答案
我认为他们的关键在于 Managed Templates on MSDN 的声明中:
If a template is not instantiated, it’s not emitted in the metadata. If a template is instantiated, only referenced member functions will appear in metadata.
这意味着 C++ 代码中未使用的函数不会出现在生成的 DLL 中,您将无法从 C# 中使用它们。要解决此问题,您可以在 C++ 代码中添加一个假函数,它引用了该函数:
void phony()
{
auto vec = gcnew Vector3fP();
vec->foo();
}
关于c# - C++/命令行界面 : functions inherited from template class are not visible in C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8495010/