use*_*974 4 c++ templates c++-concepts
我需要在 C++ 中创建一个模板类。我需要确保模板参数的类型将是一个具有 1 个 int 字段和 1 个 string 字段的类(可以有更多字段,但这些是强制性的)。
例如,在 C# 中,我可以定义一个带有方法或属性的接口,如下所示:
interface MyInterface {
int GetSomeInteger();
string GetSomeString();
}
Run Code Online (Sandbox Code Playgroud)
然后我可以在我的模板类中使用它:
class MyClass<T> where T: MyInterface {}
Run Code Online (Sandbox Code Playgroud)
有没有办法在 C++ 中做这样的事情?
C++20 为您提供了最接近 C# 的解决方案:
#include <concepts>
template <class T>
concept MyInterface = requires(T x)
{
{ x.GetSomeInteger() } -> std::same_as<int>;
};
Run Code Online (Sandbox Code Playgroud)
进而:
template <MyInterface T>
struct MyClass
{
// ...
};
Run Code Online (Sandbox Code Playgroud)