C++/CX 工厂类提供具有相同数量参数的重载构造函数

标签 c++ visual-c++ windows-runtime idl midl

我是 C++/CX、IDL 和 WRL 的新手,遇到了一个问题我不确定是我的代码有错误还是设计的限制。

我有一个 IDL,它定义了一个 IInspectable 接口(interface)及其运行时类,以及一个可以提供自定义构造函数的工厂类。该文件看起来像这样:

interface IFoo;    
runtimeclass Foo;
interface IFooFactory;    
[uuid(8543FE719-3F40-987B-BB67-6FD499210BCA), version(0.1), exclusiveto(Foo)]    
interface IFooFactory : IInspectable    
{        
    HRESULT CreateInt32Instance([in] __int32 value, [out][retval]Foo **ppFoo);
    HRESULT CreateInt64Instance([in] __int64 value, [out][retval]Foo **ppFoo);
}    

[uuid(23017380-9876B-40C1-A330-9B6AE1263F5E), version(0.1), exclusiveto(Foo)]
interface IFoo : IInspectable    
{
    HRESULT GetAsInt32([out][retval] __int32 * value);
    HRESULT GetAsInt64([out][retval] __int64 * value);
}

[version(0.1), activatable(0.1), activatable(IFooFactory, 0.1)]    
runtimeclass Foo
{
    [default] interface IFoo;
}

代码本身很简单,关键部分是在 IFooFactory 的定义中,我有两个函数将被投影到类 Foo 的构造函数中。这两个函数具有相同数量的参数,但类型不同。

当我尝试编译这个 IDL 时,编译器提示说:

在投影构造函数中有多个具有相同数量参数的工厂方法。

我在 Internet 上搜索了很长时间,但找不到任何提到此类问题的内容。在这种情况下是否不允许具有相同数量参数的重载构造函数?如果允许,我该如何修改这个IDL?如果没有,我可以使用任何解决方法吗?

最佳答案

不允许使用相同数量参数的重载构造函数,因为动态类型语言(例如 JavaScript)不知道要使用哪个构造函数。

标准方法是使用命名静态方法。

[uuid(....), version(...), exclusiveto(Foo)]
interface IFooStatics : IInspectable    
{        
    HRESULT FromInt32([in] INT32 value, [out, retval] Foo** result);
    HRESULT FromInt64([in] INT64 value, [out, retval] Foo** result);
}

[version(...)]
/* not activatable */
[static(IFooStatics)]
runtimeclass Foo
{
    [default] interface IFoo;
}

然后你会说

// C++
Foo^ foo1 = Foo::FromInt32(int32Variable);
Foo^ foo2 = Foo::FromInt64(int64Variable);

// C#
Foo foo1 = Foo.FromInt32(int32Variable);
Foo foo2 = Foo.FromInt64(int64Variable);

// JavaScript
var foo1 = Foo.fromInt32(var1);
var foo2 = Foo.fromInt64(var2);

关于C++/CX 工厂类提供具有相同数量参数的重载构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31016281/

相关文章:

visual-c++ - 分发 VC++ Redist... 已安装时运行安装程序会导致问题

c++ - 如何将 Bstr 转换为 Platform::String?

c# - Windows 8 应用程序 - MediaElement 不播放 ".wmv"文件

C++ Python 将数据从 vector 转换为 ndarray

C++ 多个具有相同名称的类

visual-c++ - 向量下标超出范围C++错误

windows-8 - 如何在应用程序中显示 Windows 8 Metro 风格磁贴?

c++ - 尝试在 Linux 上使用 Clang++ 编译 c++11 正则表达式教程时出错

c++ - 如何正确使用wxID_OK和wxID_CANCEL?

c++ - 为什么使用 openMP 的 VC++ 矩阵时间 vector 比异步更快?