c++ - 如何使 C++ 函数将整数列表隐式转换为 vector 参数?

标签 c++ initialization implicit-conversion vmat

我正在开发一个库,其函数通常采用 vector 类型(__v4si,或 4 个有符号整数的 vector )作为参数。 (请注意,到目前为止,这与 C++ STL vector 模板类无关;这是一个更原始的结构,用于让编译器生成矢量化 SIMD代码。)

在我的 C 代码中,我通常调用一个包装器宏,它接受一个 int 参数列表并初始化一个 __v4si,如下所示:

#define MakeIndex(dims...) ((__v4si){ dims })

这当然在 C++ 中也能正常工作,但我想利用 C++ 更具表现力的类型系统来清理对我的库 API 的调用。例如,我现在写的是这样的:

long idx = IndexDotProduct(MakeIndex(1, 2, 3), MakeIndex(4, 5, 6, 7));

哪个宏扩展为:

long idx = IndexDotProduct(((__v4si){1, 2, 3}), ((__v4si){4, 5, 6, 7}));

我希望能够按照以下方式写一些东西:

long idx = IndexDotProduct({1, 2, 3}, {4, 5, 6, 7});

所以,基本上(我认为)我想定义一个类,它只是原始 __v4si 类型的语法糖,但它有一个用于列表初始值设定项的隐式转换运算符。

我如何在 C++ 11 中做到这一点?

解决方案

这是一个适用于 CC++ 代码的公式(现在使用从我的库头文件复制和粘贴的更详细的名称):

typedef struct vMAT_Index {
    __v4si v;
#ifdef __cplusplus
    vMAT_Index(__v4si v) : v(v) { }
    vMAT_Index(int v0 = 0, int v1 = 0, int v2 = 0, int v3 = 0) : v((__v4si){ v0, v1, v2, v3 }) { }
#endif
} vMAT_Index;

#define vMAT_MakeIndex(dims...) ((vMAT_Index){ .v = { dims } })

static inline long
vMAT_Index_dot(vMAT_Index a,
               vMAT_Index b)
{
    __v4si c = a.v * b.v;
    return (long)c[0] + c[1] + c[2] + c[3];
}

C 代码中,您仍然像这样使用辅助宏:

long idx = vMAT_Index_dot(vMAT_MakeIndex(1, 2, 3), vMAT_MakeIndex(4, 5, 6, 7));

但是现在在 C++ 中你可以这样写:

long idx = vMAT_Index_dot({ 1, 2, 3 }, { 4, 5, 6, 7 });

感谢 nosid 提供基本答案!

最佳答案

使用隐式构造函数从大括号初始化器列表自动创建 vector 对象:

struct vector
{
    vector(__v4si v);
    vector(int i0, int i1, int i2, int i3);
};

long IndexDotProduct(vector lhs, vector rhs);

long idx = IndexDotProduct(((__v4si){ 1, 2, 3 }), { 4, 5, 6, 7 });

关于c++ - 如何使 C++ 函数将整数列表隐式转换为 vector 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15862588/

相关文章:

c++ - 将带双引号的字符串替换为带双引号的字符串

C# 方法重载解析和用户定义的隐式转换

scala - 为什么 Int 不从 Ordered[Int] 继承/扩展

C++ 类型转换与隐式构造函数

c++ - 在代码块中找不到 -lwxmsw30u_core 和 -lwxbase30u

c# - 使用 C++ 向 COM 公开托管事件

c++ - 我可以使用 std::partial_sort 对 std::map 进行排序吗?

ios - 如何桥接 Objective-C initWithError : method into Swift

objective-c - 覆盖父类(super class)的指定初始化程序

ios - 如何正确初始化类