成员变量与函数概念检查

Ric*_*ock 6 c++ c++-concepts

我沉迷于一些早期的星期天 C++20 恶作剧,在玩 gcc/clang 主干概念时,我偶然发现了一个我没有看到优雅解决方案的问题。考虑这个代码:

template <typename T>
concept floating_point = std::is_floating_point_v<std::decay_t<T>>;

template <typename T>
concept indexable = requires(T v)
{
    {v[0]} -> floating_point;
    {v[1]} -> floating_point;
    {v[2]} -> floating_point;
};

template <typename T>
concept func_indexable = requires(T v)
{
    {v.x()} -> floating_point;
    {v.y()} -> floating_point;
    {v.z()} -> floating_point;
};

template <typename T>
concept name_indexable = requires(T v)
{
    {v.x} -> floating_point;
    {v.y} -> floating_point;
    {v.z} -> floating_point;
};

template <typename T>
concept only_name_indexable = name_indexable<T> && !indexable<T>;

template <typename T>
concept only_func_indexable = func_indexable<T> && !indexable<T> && !name_indexable<T>;

void test_indexable(indexable auto v) {
    std::cout << v[0] << " " << v[1] << " " << v[2] << "\n";
}

void test_name_indexable(only_name_indexable auto v) {
    std::cout << v.x << " " << v.y << " " << v.z << "\n";
}

void test_func_indexable(only_func_indexable auto v) {
    std::cout << v.x() << " " << v.y() << " " << v.z() << "\n";
}
Run Code Online (Sandbox Code Playgroud)

(玩这个的强制性godbolt) https://godbolt.org/z/gyCAQn

现在考虑一个满足only_func_indexable以下条件的结构/类:具有成员函数x()y()z()立即导致概念检查中的编译错误name_indexable。更确切地说:

<source>: In instantiation of 'void test_func_indexable(auto:3) [with auto:3 = func_point]':

<source>:125:26:   required from here

<source>:29:6: error: 'decltype' cannot resolve address of overloaded function

   29 |     {v.x} -> floating_point;
Run Code Online (Sandbox Code Playgroud)

这有点明显,因为它.x指的是成员函数的名称,它是 a 内部的非法表达式decltype。另请注意,将name_indexable的定义更改为

template <typename T>
concept name_indexable = !func_indexable<T> && requires(T v)
{
    {v.x} -> floating_point;
    {v.y} -> floating_point;
    {v.z} -> floating_point;
};
Run Code Online (Sandbox Code Playgroud)

通过懒惰的联合评估解决了这个问题。

在这一点上,我的结论是:“每当我想检查成员变量是否存在时,我必须首先提供并检查一个概念是否存在类似命名的成员函数”。

现在这感觉相当尴尬,就像 ISO 组中的优秀人员想到了一个更优雅的解决方案一样。

在这种情况下,该解决方案是什么?

最好的,理查德

n31*_*159 0

我不确定你的问题是否真的是一个问题。x希望您永远不会拥有同时具有数据成员和成员函数的类型x,因此您func_indexable已经是这样了only_func_indexable,有了这个概念,就没有问题了。

但如果你想在那里非常精确,你可以做这样的事情

requires std::is_member_object_pointer_v<decltype(&T::x)> && floating_point<std::invoke_result_t<decltype(&T::x), T>>;
Run Code Online (Sandbox Code Playgroud)

当然,这应该包含在一些概念中,而不是每次都写。请注意,给出std::invoke_result_t<decltype(&T::x), T>了(一些参考)floatfloat x;float x();