无法绑定的内容
crossbind 绑定的是 C++ 的一个子集。超出范围的内容会被直接舍弃,不会报错,而一个小小的封装就能把它找回来。
模板没有单一的类型,所以 larger 不会被绑定;而包装它的普通函数 largerInt 会被绑定。重载按参数个数区分:describe(7, 'km') 可以使用,但接受 std::string 的那个重载与接受 int 的参数个数相同,因此无法调用到。
同样会被舍弃的还有:private 成员、运算符、第二个基类,以及数组或结构体类型的字段。涉及它不认识的类型(例如 std::pair)的函数,会在调用时失败。规则见 C++ 绑定。
试一试
调用 describe('seven', 'km') 并阅读错误信息:是哪个重载做出了响应?[■]native.h1#pragma once
#include <string>
// A template has no single type to bind. A plain function
// over it does.
template <typename T>
T larger(T a, T b) { return a > b ? a : b; }
int largerInt(int a, int b);
// Overloads are told apart by how many arguments they take,
// so only one of the first two can be reached.
std::string describe(int value);
std::string describe(const std::string &text);
std::string describe(int value, const std::string &unit);
[■]main.js2import {
initNative, largerInt, describe,
} from './native/native.h';
await initNative();
console.log('the larger:', await largerInt(3, 7));
console.log(await describe(7));
console.log(await describe(7, 'km'));
try {
console.log(await describe('seven'));
} catch (error) {
console.log(error.message);
}