我想使用 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);
}
如您所见,很明显counter、load和unload必须是私有的/受保护的,并且它们只能从Scop访问。如果我使用抽象基类,我只能约束counter和unload,但不能load(如您所见,我不知道如何处理正确的语法......)。
也许这不会改变你的答案,但问题可能更清晰一些。