【发布时间】:2020-11-10 01:50:43
【问题描述】:
我喜欢 Java 接口的特性,并期待新的 C++20 标准,引入概念。
在当前的项目中,我将对同一件事进行多个实现。其余代码应该不受此影响,并以一般“一刀切”的方式处理它们。此外,为了帮助其他人编写自己的这个可交换部分的实现,我希望有一个文档的中心位置,描述所有需要的部分。
我试着让它工作了一段时间,但我一直在为 C++20 的概念而苦苦挣扎。由于没有什么真正起作用,我用一个小例子描述了我想要的:
/* Should have a element type, like float, int, double, std::size_t,... */
template <typename Class>
concept HasElementType = requires {
typename Class::Element;
};
/* Central place for the documentation: in the concept.
* Since all relevant parts should be listed here, they can be documentated.
*/
template < typename Class, typename T>
concept HasFunctions = requires {
Class::Class(int); /* has constructor with int */
T Class::field; /* has field with name "field" of type T */
int Class::foo(T); /* has method foo, taking T, returning int */
T Class::bar(int); /* has method bar, taking int, returning T */
void Class::foobar(); /* has method foobar, taking void, returnung void */
};
/* put both togetter */
template <typename Cls>
concept MyInterface = HasElementType<Cls> && HasFunctions<Cls,typename Cls::Element>;
上述概念MyInterface 应该确保,通过my_function<MyObject>() 调用下面的函数应该适用于不同的实现MyObject ∈ {Implementaion1, Implementaion2,...}。
/* Some example function */
template<MyInterface MyObejct>
void my_function(){
using T = MyObejct::Element;
T t = 5;
MyObejct myObject(1);
T field = myObject.field;
int foo = myObject.foo(t);
T bar = myObject.bar(1);
myObject.foobar();
}
我对此有 3 个问题:
- 是否有可能通过概念来实现?
- 这是否可能看起来有点干净?由于它应该通过可访问的文档来增加可读性,因此如果概念的代码几乎不可读,它将没有用。
- 一般来说,概念是正确的方法,还是有其他/更好的方法来实现?
谢谢,莫罗
【问题讨论】:
-
请每个 stackoverflow.com 问题一个问题。
-
1.是的,2. 基于意见,但对我来说似乎很好(概念命名除外) 3. 基于意见,但似乎是个好方法,还有其他方法(根本不检查,SFINAE)
-
"我喜欢 Java 中的接口特性,并期待新的 C++20 标准,引入概念。" 这不是概念的用途。 Java“接口”只是 C++ 中的纯虚拟类。
标签: c++ c++20 c++-concepts