c++ 带约束的模板类友谊

dsekswqp  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(181)

我尝试了以下方法,但无法编译:

template<class LabelType>
    requires requires { typename LabelType::LetterType; }
class MonoidalFSA
{
    template<class T>
    friend class MonoidalFSA;
};
error: redeclaration of ‘template<class LabelType>  requires requires{typename LabelType::LetterType;} class MonoidalFSA’ with different constraints

尝试将约束添加到friend声明中,但仍然得到相同的错误。

template<class LabelType>
    requires requires { typename LabelType::LetterType; }
class MonoidalFSA
{
    template<class T>
        requires requires { typename T::LetterType; }
    friend class MonoidalFSA;
};
km0tfn4u

km0tfn4u1#

你的第二个代码片段是正确的,但是看起来gcc并不接受它,因为它认为这两个requires表达式是不等价的。
如果你把它 Package 成一个概念,它就被接受了:

template<typename LabelType>
concept HasLetterType = requires { typename LabelType::LetterType; };

template<class LabelType> requires HasLetterType<LabelType>
class MonoidalFSA
{
    template<class T> requires HasLetterType<T>
    friend class MonoidalFSA;
};

// Or simply
template<HasLetterType LabelType>
class MonoidalFSA
{
    template<HasLetterType>
    friend class MonoidalFSA;
};

相关问题