C++中的嵌套结构模板

fdbelqdn  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(198)

我想写这个代码,但它产生了一个错误。

  1. template<int N>
  2. struct A {
  3. struct B {
  4. };
  5. B f() { return B{}; }
  6. };
  7. template<typename T>
  8. constexpr bool val = false;
  9. template<int N>
  10. constexpr bool val<typename A<N>::B> = true;
  1. error: template parameters not deducible in partial specialization:
  2. 13 | constexpr bool val<typename A<N>::B> = true;

当代码运行良好时

  1. template<int N> struct A;
  2. template<int N>
  3. struct AB {
  4. };
  5. template<int N>
  6. struct A {
  7. AB<N> f() { return AB<N>{}; }
  8. };
  9. template<typename T>
  10. constexpr bool val = false;
  11. template<int N>
  12. constexpr bool val<AB<N>> = true;

我知道C++必须检查是否存在N,使得T等于A<N>::B时,这太难了。这就是为什么有一个错误。但我的问题是有没有办法将结构体B保留在A中,并为每个N定义值val<A<N>::B>
如果B被定义为对A外部的结构体的引用(例如using B = int;),我可以理解这个错误,但如果B是在A内部定义的结构体,那么就没有歧义,N很容易推导出来。

s4n0splo

s4n0splo1#

最简单的解决方案是在类之外定义它,并且在类中有一个类型别名来正常使用它:

  1. template<int N> struct A;
  2. template<int N>
  3. struct AB {
  4. friend A<N>;
  5. };
  6. template<int N>
  7. struct A {
  8. using B = AB<N>;
  9. friend B;
  10. B f() { return B{}; }
  11. };
  12. template<typename T>
  13. constexpr bool val = false;
  14. template<int N>
  15. constexpr bool val<AB<N>> = true;

这与嵌套的struct B几乎没有什么区别。

展开查看全部

相关问题