C++中的嵌套结构模板

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

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

template<int N>
struct A {
    struct B {

    };
    B f() { return B{}; }
};

template<typename T>
constexpr bool val = false;

template<int N>
constexpr bool val<typename A<N>::B> = true;
error: template parameters not deducible in partial specialization:
   13 | constexpr bool val<typename A<N>::B> = true;

当代码运行良好时

template<int N> struct A;

template<int N>
struct AB {

};

template<int N>
struct A {
    AB<N> f() { return AB<N>{}; }
};

template<typename T>
constexpr bool val = false;

template<int N>
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#

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

template<int N> struct A;

template<int N>
struct AB {
    friend A<N>;
};

template<int N>
struct A {
    using B = AB<N>;
    friend B;
    B f() { return B{}; }
};

template<typename T>
constexpr bool val = false;

template<int N>
constexpr bool val<AB<N>> = true;

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

相关问题