如何解决在C ++中基于接口强制类中的静态方法
我正在制作一个向量类,它可以选择将分配器作为模板参数。为了确保用户定义的分配器可以与向量一起使用,我提供了一个接口,该接口设置了给定分配器的最低要求。由于分配器仅用于分配和取消分配,因此它没有成员变量,并且所有方法都是静态的。有没有办法确保任何实现都具有给定的静态方法集?我知道您不能同时具有静态和虚拟方法,但是我实质上希望任何派生自base_allocator的分配器都具有一组方法,并且这些方法必须是静态的。 简而言之:您能解决c ++中的virtual static
矛盾吗?
这是我当前的代码:
// in namespace mem_core
// Interface for usage of custom allocators with the custom:: namespace containers.
template <typename T>
class base_allocator {
public:
using T_ptr = T*;
using T_ref = T&;
virtual T_ptr address(const T_ref value);
// memory methods should allocate for amount elements of type T
virtual void deallocate(T_ptr const ptr,const size_t& count) = 0;
virtual T_ptr allocate(const size_t& amount) = 0;
};
_MEMORY_CORE_END_ // namespace mem_core }
#undef _MEMORY_CORE_BEGIN_
#undef _MEMORY_CORE_END_
// default allocator CLASS TEMPLATE
template <typename T>
class allocator : public mem_core::base_allocator<T> {
public:
using value_type = T;
using T_ptr = T*;
using T_ref = T&;
static T_ptr address(T_ref value) noexcept {
return mem_core::addressof<T>(value);
}
static void deallocate(T_ptr const ptr,const size_t& count) {
mem_core::deallocate<T>(ptr,count);
}
static T_ptr allocate(const size_t& amount) {
return mem_core::allocate<T>(amount);
}
};
这当然可以,但是不能保证用户定义的分配器已使虚拟方法静态化,因为这是分配器必须在向量类中工作的要求。 例如像这样:
template <typename T,typename alloc_type = allocator<T>>
class vector {
public:
using iterator = vector_iterator<vector<T,alloc_type>>;
using T_ptr = T*;
using T_ref = T&;
using value_type = T;
private:
T_ptr m_data;
size_t m_size;
size_t m_capacity;
public:
vector() : m_data(nullptr),m_size(0),m_capacity(0) noexcept {};
vector(const size_t& initial_cap) : m_size(0) {
m_data = alloc_type::allocate(m_capacity); // Requires static allocate method
m_capacity = initial_cap;
}
// rest of vector class ...
解决方法
可能需要使用SFINAE将类的某些方法定义为静态方法。下面的示例使用了C ++ 20的概念,但是只需做一点点的工作就可以使用纯SFINAE,因为这是这里唯一需要的。本示例定义概念has_static_methods
,该概念要求一个类将“ function”和“ function2”都实现为静态方法。无论是否为虚拟的非静态方法均会失败:
#include <iostream>
#include <type_traits>
template<typename T> struct is_function : public std::false_type {};
template<typename Ret,typename ...Args>
struct is_function<Ret (*)(Args...)> : public std::true_type {};
struct not_static {
void function();
static void function2();
};
struct is_static {
static void function();
static void function2();
};
template<typename T>
concept has_static_methods = is_function<decltype(&T::function)>::value &&
is_function<decltype(&T::function2)>::value;
// Ok's template parameter type must implement both static methods.
template<has_static_methods T> void ok()
{
}
int main()
{
ok<is_static>(); // OK
ok<not_static>(); // Error,unsatisfied contsraint.
return 0;
}
通过一些额外的工作,可以使用特定签名来强制执行静态方法。
现在,请记住,这并不能真正阻止任何人使用非静态方法定义子类。这要求将任何作为参数传递给模板的类都满足此约束。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。