我有宏问题,因为它们被大括号替换.
由于我需要为不同的操作系统[WINDOWS,OSX,ANDROID,iOS]编译,我正在尝试将typedef用于基本的C++类型,以便轻松替换它们并测试性能.
由于我正在进行大量的static_cast,我认为只有在需要时才能使用宏(CPU对我的软件至关重要).所以通过这种方式,static_cast只会在类型不同时执行,而是执行类似这样的奇怪操作:
const int tv = 8;
const int tvc = static_cast<int>(8);
Run Code Online (Sandbox Code Playgroud)
因此,如果启用FORCE_USE32,它将为其选择最佳版本
因此,当我执行以下操作时,使用默认编译器的Visual Studio 2017会出现错误:
#ifndef FORCE_USE32
#define FORCE_USE32 0
#endif
#if FORCE_USE32
typedef int s08;
#define Cs08(v) {v}
#else
typedef char s08;
#define Cs08(v) {static_cast<s08>(v)}
#endif
// this line give me an error because Cs08 is replaced by {static_cast<s08>(1)} instead just static_cast<s08>(1)
std::array<s08, 3> myArray{Cs08(1), 0, 0};
Run Code Online (Sandbox Code Playgroud)
我知道在我做数组之前我可以轻松地创建一个变量,就像这样
const s08 tempVar = Cs08(1);
std::array<s08, 3> myArray{tempVar, 0, 0};
Run Code Online (Sandbox Code Playgroud)
但我不明白原因,我希望尽可能保持我的代码清洁.有没有办法在数组定义中包含宏?
你正试图解决一个非问题
const int tvc = static_cast<int>(8);
Run Code Online (Sandbox Code Playgroud)
这里不会使用任何CPU周期.你觉得编译器现在多么愚蠢?即使没有优化,上面的演员也是无操作(无操作).不会为演员阵容生成任何其他说明.
auto test(int a) -> int
{
return a;
}
auto test_cast(int a) -> int
{
return static_cast<int>(a);
}
Run Code Online (Sandbox Code Playgroud)
如果未启用优化,则两个函数会生成相同的代码:
test(int): # @test(int)
push rbp
mov rbp, rsp
mov dword ptr [rbp - 4], edi
mov eax, dword ptr [rbp - 4]
pop rbp
ret
test_cast(int): # @test_cast(int)
push rbp
mov rbp, rsp
mov dword ptr [rbp - 4], edi
mov eax, dword ptr [rbp - 4]
pop rbp
ret
Run Code Online (Sandbox Code Playgroud)
随着-O3他们得到:
test(int): # @test(int)
mov eax, edi
ret
test_cast(int): # @test_cast(int)
mov eax, edi
ret
Run Code Online (Sandbox Code Playgroud)
回到编译器(实际上是优化算法)是多么聪明,通过启用优化,编译器可以做疯狂的疯狂事情,例如循环展开,将递归函数转换为迭代函数,删除整个冗余代码以及依次开启.你正在做的是过早优化.如果您的代码对性能至关重要,那么您需要对汇编,编译器优化和系统架构有一个正确的理解.然后你不要盲目地优化你认为缓慢的东西.您首先编写可读性代码,然后进行配置.
回答你的宏问题:只需{}从宏中删除:
#define Cs08(v) v
#define Cs08(v) static_cast<s08>(v)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |