5

我想使用 Concepts TS 来帮助我进行数据约束。我将讨论p0121r0中讨论的概念,并且我使用 GCC 6.2 进行测试。

看这段简单的代码:

template<typename T>
concept bool test_is_available = requires(T t) {
    t.test;
    { t.test++ };
    { t.test-- };
};

template<test_is_available T>
struct Tester
{
    T t;
};

我必须将具有test属性的类型传递给 struct Tester ,该类型是可递增和可递减的。好的。

struct A
{
    unsigned test;
}

Tester<A> a;

按预期工作。显然,下面的一个是行不通的:

struct B
{
    std::string test;
};

struct C
{
    unsigned not_test;
};

Tester<B> b; // error: test++ and test-- are ill formed
Tester<C> c; // error: no test available

现在,真正的问题是:为什么以下一个不起作用?

class D
{
    unsigned test;
};

Tester<D> d; // error: private???

我试图深入研究标准论文,但我无法理解这种行为是预期的,如果标准本身缺少这种可能性,如果编译器无法正常工作......

或者,也许我需要声明一种友谊,但这有什么意义呢?在这种情况下,概念约束不需要受到访问者的约束......

对这里发生的事情有任何想法吗?

编辑: 用一个简单的例子来说明问题的想法并不总是那么容易。这个有点复杂,但更类似于真实案例:

#include <cassert>
#include <utility>

template<typename T>
concept bool Countable = requires(T t) {
    t.counter;
    { ++t.counter };
    { --t.counter };
    //{ t.load(auto&&...) } -> void; <-- I am not sure how to handle this
    { t.unload() } -> void;
};

template<Countable T>
class Scoper
{
public:
    template<typename... Args>
    Scoper(T& t, Args... args) : m_t(&t)
    {
        ++t.counter;
        t.load(std::forward<Args>(args)...);
    }

    ~Scoper()
    {
        --m_t->counter;
        m_t->unload();
    }

private:
    T* m_t;
};

class Scopeable
{
public:
    unsigned getCounter() const
    {
        return counter;
    }

//private:
    //template<Countable> friend class Scoper; <-- does not work
    void load(char, int) {}
    void unload() {}
    unsigned counter = 0;
};

int main()
{
    Scopeable scopeable;
    assert(scopeable.getCounter() == 0);
    {
        Scoper<Scopeable> scoper(scopeable, 'A', 2);
        assert(scopeable.getCounter() == 1);
    }
    assert(scopeable.getCounter() == 0);
}

如您所见,很明显counterloadunload必须是私有的/受保护的,并且它们只能从Scop访问。如果我使用抽象基类,我只能约束counterunload,但不能load(如您所见,我不知道如何处理正确的语法......)。

也许这不会改变你的答案,但问题可能更清晰一些。

4

1 回答 1

10

这个概念:

template<typename T>
concept bool test_is_available = requires(T t) {
    t.test;
    { t.test++ };
    { t.test-- };
};

要求T具有可公开访问的成员test,该成员既可后递增又可后自减。

这个类型:

class D
{
    unsigned test;
};

没有可公开访问的成员测试。毕竟,我不能写任何这些陈述:

D d;
d.test;   // error
d.test++; // error
d.test--; // error

因此,D不符合概念test_is_availabletest非常不可用。

如果你想D成为一个test_is_available,你需要做test public。你不能简单地friend破坏概念系统——你最终会得到一个Dtest_is_available某些类型但不是其他类型的东西。这不是事情应该如何运作的。

于 2016-09-30T13:12:52.680 回答