c++概念生命和类型别名声明

C++ concepts lite and type alias declaration

本文关键字:类型 别名 声明 生命 c++      更新时间:2023-10-16

是否可以使用typedefusing在概念内声明类型别名,如概念TS所建议的?如果我尝试下面的MWE,代码无法编译(使用gcc 6.2.1和-fconcepts开关)

#include <type_traits>
template<typename T>
concept bool TestConcept ()
{
    return requires(T t)
    {
        using V = T;
        std::is_integral<V>::value;
    };
}
int main()
{
    return 0;
}

产生的错误:

main.cpp: In function ‘concept bool TestConcept()’:
main.cpp:8:9:  error: expected primary-expression before ‘using’  
         using V = T;  
         ^~~~~   
main.cpp:8:9: error: expected ‘}’ before ‘using’
main.cpp:8:9: error: expected ‘;’ before ‘using’
main.cpp:4:14: error: definition of concept ‘concept bool TestConcept()’ has multiple  statements
 concept bool TestConcept ()  
              ^~~~~~~~~~~ 
main.cpp: At global scope:
main.cpp:11:1: error: expected declaration before ‘}’ token
 } 
 ^

No。根据TS概念,需求是:

需求:
,,, simple-requirement
,,, 要求
,,, compound-requirement
,,, nested-requirement

其中简单需求是一个表达式后面跟着一个;类型需求是类似typename T::inner的东西。另外两个听起来和名字一样。

类型别名是声明,而不是表达式,因此不满足需求的要求。

这对我来说是不必要的限制。您知道是否存在一种合理的解决方法,而不是一遍又一遍地编写相同的复杂类型吗?

您可以将约束的实现推迟到另一个概念,将这些类型作为模板参数传递:

template<typename Cont, typename It, typename Value>
concept bool InsertableWith = requires(Cont cont, It it, Value value) {
    // use It and Value as much as necessary
    cont.insert(it, std::move(value));
};
template<typename Cont>
concept bool Insertable = requires {
    // optional
    typename Cont::const_iterator;
    typename Cont::value_type;
} && InsertableWith<Cont, typename Cont::const_iterator, typename Cont::value_type>;

如果你正在考虑这样做,我建议你在做决定之前先在简单的例子上尝试一下。如何编写概念和约束决定了编译器将如何报告错误,当然,良好的错误是使概念有用的重要组成部分。让我的概念更容易写,同时让错误更难以理解,这不是我可以轻易取舍的。

例如,这就是为什么我冗余地添加typename Cont::const_iterator;作为显式约束。这使编译器有机会报告此类型需求。在选择InsertableWith作为概念名称时,我也很小心:我本可以轻松地使用detail::Insertable,但同时涉及Insertabledetail::Insertable的错误可能会更加令人困惑。

最后请注意,这一切都依赖于编译器实现的质量,所以我暂时不期望任何方法是确定的。