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

visual C++/CX factory class to provide overloaded constructors with same number of arguments

本文关键字:参数 构造函数 重载 CX C++ 工厂 visual      更新时间:2023-10-16

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

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

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时,编译器会抱怨:

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

我在网上搜索了很长一段时间,但没有找到任何提到这类问题的东西。在这种情况下,是否不允许具有相同数量参数的重载构造函数?如果允许,我应该如何修改这个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);