是否可以使用C++可变参数来定义一个允许以下调用的函数:
f(int, char)
f(int, char, char)
f(int, char, char, int)
f(int, char, char, int, char)
...
Run Code Online (Sandbox Code Playgroud)
其中每个第n个参数是a,char如果n是素数,否则它是a int.该功能只能以这种方式调用; 它不能与其他参数模式一起编译(例如f(2, 2)是一个错误,但f(2, '2')没关系).
我想要一个静态断言来确保给定的表达式是字符串文字。我试过这个:
#define SAME_TYPES(x, y) __builtin_types_compatible_p(typeof(x), typeof(y))
#define IS_ARRAY(x) !SAME_TYPES((x), &(x)[0])
#define IS_COMPILE_TIME_STR(x) IS_ARRAY(x) && #x[0] == '"'
#define ASSERT_COMPILE_TIME_STR(x) static_assert(IS_COMPILE_TIME_STR(x), "Only static allocated compile time strings are allowed, but got this: " #x)
/*
* ASSERT_COMPILE_TIME_STR("hey"); <-- this is fine
* ASSERT_COMPILE_TIME_STR(1234); <-- this should fail
*/
Run Code Online (Sandbox Code Playgroud)
不幸的是,ASSERT_COMPILE_TIME_STR不起作用,因为#x[0] == '"'似乎不是编译时常量。
还有其他方法可以实现这一目标吗?它只需要使用 gcc 进行编译,所以任何类型的扩展都可以:)
多谢
我开始学习机器学习.现在我试着玩tensorflow.
我常常看到这样的例子:
pred = tf.add(tf.mul(X, W), b)
Run Code Online (Sandbox Code Playgroud)
我也在一个简单的numpy实现中看到了这样一条线.为什么总是x*W+b用而不是W*x+b?如果矩阵以这种方式成倍增加是否有优势?我看到它是可能的(如果X,W并且b被转置),但我没有看到优势.在数学课上我们总是只使用Wx+b.
非常感谢你
How do I implement an apply_n_times function which gets a function f: T -> T and a number n and the result will be a function which applies f ntimes?
E.g. apply_n_times(f, 0) equals |x| x and apply_n_times(f, 3) equals |x| f(f(f(x))).
There is no deeper sense in this function, I just want to implement it for learning reasons.
My current code:
fn apply_n_times<T>(f: Fn(T) -> T, n: i32) -> dyn Fn(T) -> T {
if n < …Run Code Online (Sandbox Code Playgroud) 我已经意识到并读到将 auint16_t与另一个uint16_t相乘会得到一个整数(它实际上似乎是一个有符号整数?请参阅:)。鉴于此,我是否必须假设以下函数f会产生未定义的行为,因为会出现有符号整数溢出?
会发生溢出,因为x*x对于x=45000“几乎”的结果INT32_MAX,如果再次乘以 就会溢出x。
(顺便说一句:在我的平台上int是一个int32_t)
#include <stdio.h>
#include <stdint.h>
uint16_t f(uint16_t x) {
printf("%zu\n", sizeof(x)); // <-- 2
printf("%zu\n", sizeof(x * x)); // <-- 4
return x * x * x;
}
int main()
{
uint16_t x = 45000;
uint16_t y = f(x);
}
Run Code Online (Sandbox Code Playgroud)
会发生溢出,因为x*x对于x=45000“几乎”的结果INT32_MAX,如果再次乘以 就会溢出x。
这是正确的,还是我做出了一些错误的假设?
假设我在 C 中有一个这样的数组:
static volatile bool my_array[128] = {0};
Run Code Online (Sandbox Code Playgroud)
最重要的是,我有 128 个线程,每个线程在完成时都会写入不同的索引。true
这会产生一些问题吗?在 x64 上写入单个字节不会影响周围的字节,对吗?
我只是问,因为我不确定CPU/内存控制器/等是否总是读取8(或4)字节,然后写入它们。这会产生一些奇怪的竞争条件。
多谢