parallel101 / course

高性能并行编程与优化 - 课件
https://space.bilibili.com/263032155
Other
3.62k stars 532 forks source link

print 函数打印模版特化问题 #26

Closed jr981008 closed 11 months ago

jr981008 commented 11 months ago
#include "print.h"
template<typename T>
class TypeToID{
public:
    static int const  ID=-1;
};
template<> class TypeToID<void*>{
public:
   static  int const  ID=1;
};
int main(){

    print(TypeToID<void *>::ID);

    return 0;

}

链接报错 找不到符号 .rdata$.refptr._ZN8TypeToIDIPvE2IDE[.refptr._ZN8TypeToIDIPvE2IDE]+0x0): undefined reference to `TypeToID<void*>::ID'

archibate commented 11 months ago

这不是我print的问题,任何其他试图以int const &按引用获取你这个ID变量的都会爆这个错。 static int const ID=1; // 错误!需要另外开辟一个文件写int const Type::ID=1;来满足odr规则!否则是未定义行为

改成: inline static constexpr int ID=1; // cpp27支持用inline修饰绕开odr规则

顺便一提,古代cpp我们都是用enum { ID = 1; }来定义类内常量的

无法顺畅的大口呼吸,是活着的最好证明

---原始邮件--- 发件人: @.> 发送时间: 2023年10月11日(周三) 下午3:20 收件人: @.>; 抄送: @.***>; 主题: [parallel101/course] print 函数打印模版特化问题 (Issue #26)

include "print.h"

template class TypeToID{ public: static int const ID=-1; }; template<> class TypeToID<void>{ public: static int const ID=1; }; int main(){ print(TypeToID<void >::ID); return 0;
} 链接报错 找不到符号 .rdata$.refptr._ZN8TypeToIDIPvE2IDE[.refptr._ZN8TypeToIDIPvE2IDE]+0x0): undefined reference to `TypeToID<void*>::ID'

— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you are subscribed to this thread.Message ID: @.***>

jr981008 commented 11 months ago

妙enum { ID = 1; } 感谢