gpt4 book ai didi

没有模板函数继承的 C++ 接口(interface)

转载 作者:行者123 更新时间:2023-12-03 08:11:40 25 4
gpt4 key购买 nike

有两个不同的类具有交叉的方法集:

class A {
public:
int Value1() { return 100; }
char Value2() { return "a"; }
void actionA() { };
}

class B {
public:
int Value1() { return 200; }
char Value2() { return "b"; }
void actionB() { };
}

类接口(interface)的公共(public)部分可以这样描述:

class GenericPart {
public:
virtual int Value1();
virtual char Value2();
}

请注意,类 AB 来自某个库,因此不能从 GenericPart 继承。

有一个模板函数可以与实现GenericPart中描述的方法的对象一起使用:

template <typename T>
void function(T record) {
std::cout << record.Value1() << " " << record.Value2() << std::endl;
}

是否可以专门化此模板函数以使其仅接收与 GenericPart 匹配的对象?

最佳答案

您可以使用 C++20 功能:concepts & constraints ,但更简单的解决方案可能涉及 static_assert。解释见function中的注释

#include <type_traits>
#include <iostream>

class A {
public:
int Value1() { return 100; }
char Value2() { return 'a'; }
void actionA() { };
};

class B {
public:
int Value1() { return 200; }
char Value2() { return 'b'; }
void actionB() { };
};

class C { // Has the required functions but with different return types
public:
double Value1() { return 0.0; }
double Value2() { return 1.0; }
};

class D { // Has only one required function
public:
int Value1() { return 300; }
};


template <typename T>
void function(T record) {
// Check statically that T contains a `Value1()` that returns an int
static_assert(std::is_same_v<int, decltype(record.Value1())>, "int Value1() required!");

// Check statically that T contains a `Value2()` that returns an char
static_assert(std::is_same_v<char, decltype(record.Value2())>, "char Value2() required!");

std::cout << record.Value1() << " " << record.Value2() << std::endl;
}

int main()
{
A a;
B b;
C c;
D d;

function(a); // Ok
function(b); // Ok
function(c); // causes static_assert to fail
function(d); // causes static_assert to fail
}

关于没有模板函数继承的 C++ 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60512637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com