跳至主要內容
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?

4563博客

全新的繁體中文 WordPress 網站
  • 首頁
  • c++ 模版编译问题, func -> bool { if constexpr A else B } 和直接声明 static constexpr bool 编译的区别
未分類
20 1 月 2022

c++ 模版编译问题, func -> bool { if constexpr A else B } 和直接声明 static constexpr bool 编译的区别

c++ 模版编译问题, func -> bool { if constexpr A else B } 和直接声明 static constexpr bool 编译的区别

資深大佬 : sl0000 33

struct is {     template<typename T>     static constexpr bool _vector() {         if constexpr (std::is_fundamental_v<T>) {             return false;         } else {             return std::is_same_v<T, std::vector<typename T::value_type>>;         }     }     template<typename T>     static constexpr bool vector = _vector<T>();          template<typename T>     static constexpr bool vector2 = std::is_fundamental_v<T> || (!std::is_fundamental_v<T> && std::is_same_v<T, std::vector<typename T::value_type>>); };    int main(int argc, const char * argv[]) {     std::cout << is::vector2<std::vector<std::vector<int>>::value_type::value_type> << std::endl;     return 0; } 

使用 vector 是 ok 的

使用 vector2 编译会报 Type ‘int’ cannot be used prior to ‘::’ because it has no members

大佬有話說 (10)

  • 資深大佬 : q2577

    “`
    template<class T>
    struct is_vector {
    static constexpr bool value = false;
    };
    template<class T>
    struct is_vector<std::vector<T> > {
    static constexpr bool value = true;
    };
    ““

  • 主 資深大佬 : sl0000

    @q2577 居然这么简单。。。但是 上面的编译问题 能解释一下吗

  • 資深大佬 : q2577

    @sl0000 可能是编译器问题?

  • 資深大佬 : L4Linux

    vector2 逻辑操作左右两边在编译时都会求值,所以出现了 int::value_type 。

  • 資深大佬 : GeruzoniAnsasu

    @L4Linux 不能叫「左右两边都求值」吧,我觉得应该叫「模板替换不受表达式本身的逻辑影响」,就,这个表达式本身的逻辑成不成立并不影响用 int 去替换 T ,这个过程也并没有触发 SFINAE ,所以替换失败,编译报错
    @sl0000 那么如果用 SFINAE 来容纳替换错误的表达式,就可以工作了:
    https://gcc.godbolt.org/z/eE5Gar4z3

  • 資深大佬 : edimetia3d

    虽然很不想回, 但是既然都看了. 还是回复一下吧.
    1. 麻烦问问题前把代码清理一下, 整理一个最简单的 case 出来.
    2. @L4Linux 正解
    3. 你把 `if constexpr` 换成 `if`也会编译出错, 一样的道理, 至于这个道理你懂不懂, 就看你了.

  • 資深大佬 : test0x01

    我发现,十五年没用 c++, 基本上看不懂了

  • 資深大佬 : Caturra

    泛型编程中这种伪·短路运算是不管用的,实例化出来编译器看不懂就是不行( int::value_type ),
    但是传统上可以用 SFINAE 或者简单点直接上特化来解决问题
    相比之下 if-constexpr 可读性也挺好,不用写一堆 struct (我也想多用点 17 的特性唉

  • 資深大佬 : GeruzoniAnsasu

    @sl0000
    发现#5 的代码写错了,改正了一点细节,这个例子可以工作
    https://gcc.godbolt.org/z/h3nnch497

  • 資深大佬 : GeruzoniAnsasu

    另外这个 constexpr if 填补了我一个知识空白:
    constexpr 也有类似两段名字查找的特性,如果定义在模板中,那么否定分支中的代码会直接丢弃;如果处于模板实例化阶段,则会正常替换分支两侧的所有需要实例化的模板代码
    https://stackoverflow.com/questions/50051473/if-constexpr-in-c17-does-not-work-in-a-non-templated-function
    我们吸艹真的太牛逼辣

文章導覽

上一篇文章
下一篇文章

AD

其他操作

  • 登入
  • 訂閱網站內容的資訊提供
  • 訂閱留言的資訊提供
  • WordPress.org 台灣繁體中文

51la

4563博客

全新的繁體中文 WordPress 網站
返回頂端
本站採用 WordPress 建置 | 佈景主題採用 GretaThemes 所設計的 Memory
4563博客
  • Hostloc 空間訪問刷分
  • 售賣場
  • 廣告位
  • 賣站?
在這裡新增小工具