c++ - 接受派生类对象的派生类中的 C++ 强制函数
问题描述
我希望从我的基类派生的所有类都具有此功能:
class Derived : public Base{
public:
void doSth(const Derived& d){
...
}
}
这可以在我的基类中强制执行吗?
class Base{
public:
virtual void doSth(const Base& b) = 0; // ?
}
解决方案
不,虚拟功能没有帮助,因为您更改了它的签名。这是一个依赖 C++11 特性的可能实现。它正确检测具有所需签名的功能。
#include <type_traits>
template<typename, typename T>
struct has_doSth {
static_assert(
std::integral_constant<T, false>::value,
"Second template parameter needs to be of function type.");
};
// specialization that does the checking
template<typename C, typename Arg>
struct has_doSth<C, void(Arg)> {
private:
template<typename T>
static constexpr auto check(T*)
-> typename
std::is_same<
decltype( std::declval<T>().doSth( std::declval<Arg>()) ),
void
>::type; // attempt to call it and see if the return type is correct
template<typename>
static constexpr std::false_type check(...);
typedef decltype(check<C>(0)) type;
public:
static constexpr bool value = type::value;
};
template<typename T>
class Base {
public:
Base() {
static_assert(has_doSth<T, void(const T&)>::value, "Missing required function in the derived class.");
}
};
用法:
class WellDerived : public Base<WellDerived> {
public:
void doSth(const WellDerived& d){
...
}
};
class BadDerived : public Base<BadDerived> {
public:
void doSth(int d){
...
}
};
推荐阅读
- jsonschema - 如何指定 Liquid Studio 创建的 json 模式中的属性顺序?
- html - Bootstrap 4响应间距(填充)不起作用
- java - 如何使用java获取下个月的前三个日期
- python - 如何在 cython 中优化 jonswap 频谱
- micronaut - Micronaut / 车把助手
- c - 在方法中传递数组并获取它的大小
- google-bigquery - Dataproc 上 Spark 的 BigQuery 连接器 - 无法使用服务帐户密钥文件进行身份验证
- c# - 从列表中添加和删除时出现“索引超出范围”错误
- c++ - vcpkg 致命错误:即使文件存在,也找不到“muParser.h”文件
- django - Django: forms.ChoiceField, overriding forms __init__