visual C++/CX工厂类,为重载构造函数提供相同数量的参数
visual C++/CX factory class to provide overloaded constructors with same number of arguments
我是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);
相关文章:
- C++:使用运算符 = 调用多参数构造函数
- 通过零参数构造函数创建的 glm::mat4 应该包含哪些值?
- 好奇的混合与可变参数构造函数
- 具有默认值的单个参数构造函数是否与默认构造函数相同?
- 为什么我们需要创建一个单参数构造函数来使用临时的无名称对象
- 在可变参数构造函数中初始化常量数组
- C++ 显式多参数构造函数歧义
- 零一参数构造函数
- 可变参数构造函数中的 SFINAE
- 当没有显式关键字与单参数构造函数一起使用时,编译器可以发出警告
- 可变参数类模板和可变参数构造函数
- 确保模板参数类型与其可变参数构造函数的类型匹配
- C++默认参数构造函数与内联初始化优先级
- 如何在 c++ 中将包含复制构造函数的类的参数构造函数称为私有?
- 自动存储中没有无参数构造函数的类对象和异常
- 警告:用两个参数构造函数返回对象时,表达结果未使用
- 如何在C++中调用无参数构造函数
- 在 c++ 中具有多个参数构造函数的模板类存在问题
- 可变参数构造函数优先于用户提供的移动构造函数,除非默认
- 如何从可变参数构造函数参数构造任何对象?