小编The*_*ang的帖子

在C中创建"类",在堆栈上与堆相比?

每当我看到一个C"类"(通过访问将指针作为第一个参数的函数来使用的任何结构)时,我看到它们实现如下:

typedef struct
{
    int member_a;
    float member_b;
} CClass;

CClass* CClass_create();
void CClass_destroy(CClass *self);
void CClass_someFunction(CClass *self, ...);
...
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它CClass_create始终malloc是内存并返回指向它的指针.

每当我看到newC++不必要地出现时,它似乎通常会让C++程序员疯狂,但这种做法在C中似乎是可以接受的.为什么堆分配的结构"类"如此常见?

c heap stack struct

47
推荐指数
4
解决办法
5102
查看次数

为什么Clang不带标准库头?

我从这个网站下载了Clang 3.6.2,并尝试使用Windows下的Code :: Blocks进行设置.不幸的是,由于它不知道在哪里,它无法编译一个简单的"hello world"程序iostream.

查看安装文件夹,它似乎没有包含标准库.为什么?我怎么得到它?

c++ clang standard-library llvm-clang

15
推荐指数
1
解决办法
7476
查看次数

如何为内置类型的arithmitic操作提升两种模板类型呢?

如果我有一个通用的struct/class:

template<typename T>
struct Container
{
    T value;
    Container(const Value& value) : value(value) { }
};
Run Code Online (Sandbox Code Playgroud)

我想对其中两个执行操作:

template<typename T, typename U>
Container<T> operator+(const Container<T>& lhs, const Container<U>& rhs)
{
    return Container<T>(lhs.value + rhs.value);
}
Run Code Online (Sandbox Code Playgroud)

问题是,如果lhs是类型Container<int>rhs类型Container<float>,那么我会Container<int>回来.但是,如果我这样做auto result = 2 + 2.0f,那么result就是那种类型float.因此内置类型和自定义类型之间的行为不一致.

那么我将如何处理operator+重载并使其返回Container<float>,就像C++如何使用内置类型处理算术推广一样?

c++ templates arithmetic-expressions c++11 type-promotion

5
推荐指数
1
解决办法
375
查看次数

为什么Lua C函数中的参数值显示在堆栈的底部?

以lua的简单C函数为例:

int luacfunc(lua_State *L)
{
    printf("%g\n", lua_tonumber(L, 1) + lua_tonumber(L, 2));
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,参数显示为索引12.由于正数表示堆栈自下而上,这意味着参数位于堆栈的底部,而不是顶部.

为什么会这样?它是否需要在每个函数调用上移动整个堆栈以为参数腾出空间?

c lua stack virtual-machine

2
推荐指数
1
解决办法
73
查看次数

为什么不能隐式转换模板类型参数?

鉴于此代码:

template<typename T>
struct Type
{
    T value;
};

template<typename T>
Type<T> operator+(const Type<T>& type, T val)
{
    Type<T> type;
    type.value += val;
    return type;
}

int main()
{
    Type<float> type;
    type = type + 2;
}
Run Code Online (Sandbox Code Playgroud)

我在MSVC中收到错误:

Error C2782 'Type<T> operator +(const Type<T> &,T)': template parameter 'T' is ambiguous

Error C2676 binary '+': 'Type<float>' does not define this operator or a conversion to a type acceptable to the predefined operator 

Error no operator "+" matches these operands
Run Code Online (Sandbox Code Playgroud)

我认为它只会将int提升为浮点数,但显然它不想这样做.有办法解决这个问题吗?

c++ templates types type-conversion

0
推荐指数
1
解决办法
61
查看次数