小编Yur*_*yro的帖子

模板别名的上下文中的模板<> template <>语法是什么?

(这个问题与模板模板参数无关.)

我刚刚发现GCC编译了这样的代码

template <typename A, typename B>
struct P {};

template <typename A>
template <typename B>
using Q = P<A, B>;
Run Code Online (Sandbox Code Playgroud)

哪个Q是双重模板的名字.

但我不能用这个.当我写作时Q<short><long>,我明白了

template_template.cpp:10:5: error: ‘Q<short int>’ is not a template
     Q<short><long>{};
     ^~~~~~~~
template_template.cpp:10:20: error: invalid use of incomplete type ‘Q<short int>’
     Q<short><long>{};
                    ^
template_template.cpp:2:8: note: declaration of ‘Q<short int>’
 struct P {};
Run Code Online (Sandbox Code Playgroud)

为什么编译第一个片段?

是否有语法来说服编译器Q<short>实际上是一个模板?

// GCC 6.3.0

c++ templates

16
推荐指数
1
解决办法
642
查看次数

为什么编译器会假设这些看似相等的指针不同?

看起来GCC有一些优化认为来自不同翻译单元的两个指针永远不会相同,即使它们实际上是相同的.

码:

main.c中

#include <stdint.h>
#include <stdio.h>

int a __attribute__((section("test")));
extern int b;

void check(int cond) { puts(cond ? "TRUE" : "FALSE"); }

int main() {
    int * p = &a + 1;
    check(
        (p == &b)
        ==
        ((uintptr_t)p == (uintptr_t)&b)
    );
    check(p == &b);
    check((uintptr_t)p == (uintptr_t)&b);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

公元前

int b __attribute__((section("test")));
Run Code Online (Sandbox Code Playgroud)

如果我用-O0编译它,它会打印出来

TRUE
TRUE
TRUE
Run Code Online (Sandbox Code Playgroud)

但是用-O1

FALSE
FALSE
TRUE
Run Code Online (Sandbox Code Playgroud)

所以p并且&b实际上是相同的值,但是编译器优化了它们的比较,假设它们永远不会相等.

我无法弄清楚,哪种优化做到了这一点.

它看起来不像严格的别名,因为指针是一种类型,而-fstrict-aliasing选项不会产生这种效果.

这是记录在案的行为吗?或者这是一个错误?

c gcc pointers compiler-optimization language-lawyer

12
推荐指数
2
解决办法
824
查看次数