代码之家  ›  专栏  ›  技术社区  ›  jcarpenter2

概念是否需要constexpr值或函数?

  •  5
  • jcarpenter2  · 技术社区  · 8 年前

    所以,我想做一些高级类型级别的黑客,我真的希望能够编写一个需要类型具有 constexpr int 与之关联的值,稍后我可以在与整数相同的概念中使用它 std::array 模板参数。

    可以写

    template<typename T>
    concept bool HasCount = requires {
        typename T::count;
    };
    

    但这不是我想要的;我想 T::count 成为一名 static constexpr int 但是,代码(甚至不包括所需的 constexpr )

    template<typename T>
    concept bool HasCount = requires {
        int T::count;
    };
    

    在GCC 7.3.0上编译时未出现“错误:应在“int”之前使用主表达式”。

    另一次失败的尝试:可以编写此文件,这需要 static int T::count() :

    template<typename T>
    concept bool HasCount = requires {
        {T::count()} -> int;
    };
    

    但这不是我想要的:

    template<typename T>
    concept bool HasCount = requires {
        {T::count()} -> constexpr int;
        {T::count() constexpr} -> int; // or this
        {constexpr T::count()} -> int; // or this (please forgive me for fuzzing GCC instead of reading the manual, unlike perl C++ is not an empirical science)
    };
    

    所以,我想知道是否有可能要求概念表达式为constexpr限定的,或者是否有可能,是否有不可能的原因,或者是否只是没有包含在规范中。

    1 回复  |  直到 8 年前
        1
  •  5
  •   Casey    8 年前

    理论上,这可以通过要求 T::count 是一个有效的表达式,并要求它的使用是有效的 T: :计数 在需要常量表达式的上下文中。例如:

    #include <type_traits>
    #include <utility>
    
    template<int> using helper = void;
    
    template<typename T>
    concept bool HasCount = requires {
        // T::count must be a valid expression
        T::count;
        // T::count must have type int const
        requires std::is_same_v<int const, decltype(T::count)>;
        // T::count must be usable in a context that requires a constant expression
        typename ::helper<T::count>;
    };
    
    struct S1 {
        static constexpr int count = 42;
    };
    static_assert(HasCount<S1>);
    
    struct S2 {
        int count = 42;
    };
    static_assert(!HasCount<S2>);
    
    struct S3 {
        static constexpr double count = 3.14;
    };
    static_assert(!HasCount<S3>);
    

    但实际上, the implementation of concepts in GCC rejects this program :

    <source>:20:16: error: invalid use of non-static data member 'S2::count'
     static_assert(!HasCount<S2>);
                    ^~~~~~~~~~~~
    <source>:18:17: note: declared here
         int count = 42;
                     ^~
    <source>:20:16: error: invalid use of non-static data member 'S2::count'
     static_assert(!HasCount<S2>);
                    ^~~~~~~~~~~~
    <source>:18:17: note: declared here
         int count = 42;
                     ^~
    

    (哪个事实 I believe to be a bug .)