gpt4 book ai didi

c++ - 模板参数子类型的使用(进阶案例)

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:43:30 26 4
gpt4 key购买 nike

我有几个具有以下继承关系的类:

template <typename ID_t>
class Identifiable {
public:
virtual ID_t unique_ID() const {
return 0;
}
};
template <typename DerivedName>
class SomeBase : public Identifiable<typename DerivedName::ID_t> {
public:
virtual DerivedName & instance() = 0;
};
template <uint16_t SomeParam = 5>
class SomeDerived : public SomeBase<SomeDerived<SomeParam>> {
public:
using ID_t = uint16_t;
SomeDerived & instance() override {
return *this;
}
ID_t unique_ID() const override {
return SomeParam;
}
};
int main() {
std::cout << "Hello, World!\n";
SomeDerived<> instance;
std::cout << std::to_string(instance.unique_ID()) << std::endl;
}

但这不会在 SomeBase 声明行中使用“No type named ID_t in class SomeDerived”进行编译。尽管接缝的原因很明显,有没有办法在没有这个检查的情况下强制编译?或者在不将 ID_t 作为另一个模板参数传递的情况下修复它?

这是沙箱的链接:cpp.sh/57ox6

最佳答案

您缺少来自 Identifiable 的类型别名:

template <typename ID>
class Identifiable {
public:
using ID_t = ID;
virtual ID_t unique_ID() const {
return 0;
}
};

关于c++ - 模板参数子类型的使用(进阶案例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44210353/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com