【发布时间】:2023-03-21 03:25:01
【问题描述】:
基本上,我正在尝试创建一个模板类,该类可以以用户友好的方式或以提供更多可配置性的更复杂的方式进行实例化。我想提供这两种实例化方法而无需复制 API。
该类看起来类似于:
// templates that offer a lot of configurability
template<typename T, typename some_probably_awful_to_type_nested_class>
class has_my_api {
};
// templates that are easy to use
template<typename T, int i>
class has_my_api {
};
我的想法是我可以使用i 构建some_probably_awful_to_type_nested_class 的通用版本,但是这两个类将调用完全相同的api。
我知道我可以通过使用带有实际 API 的内部类型来做到这一点,并且让这两个类中的每一个的 API 只调用该内部类,但我正在寻找一种方法来做到这一点而无需重复代码。
这是我正在寻找的更具体的示例:
#define DEFAULT_CONFIG 0
//////////////////////////////////////////////////////////////////////
// Nested classes themselves
template<typename T>
class inner_nested_class {
// some fairly complex api
};
template<typename T,
typename inner_nested_class_t,
int configuration_flags = DEFAULT_CONFIG>
class outer_nested_class {
// some data structure of inner_nested_class
};
//////////////////////////////////////////////////////////////////////
// Helpers for creating nested_class from int seed
template<typename T, int i>
struct nested_class_creator;
template<typename T>
struct nested_class_creator<T, 0> {
typedef inner_nested_class<T> type;
};
template<typename T, int i>
struct nested_class_creator {
typedef outer_nested_class<T, typename nested_class_creator<T, i - 1>::type> type;
};
template<typename T, typename outer_nested_class_t>
class manager_class {
manager_class() = default;
int foo();
int bar();
int baz();
// some fairly involved additional API...
};
/* What i do NOT want to do
template<typename T, typename outer_nested_class_t>
class manager_class_api {
manager_class<T, outer_nested_class_t> inner_m;
int foo() { return inner_m.foo() };
int bar() { return inner_m.bar() };
int baz() { return inner_m.baz() };
};
template<typename T, int i>
class manager_class_api {
manager_class<T, typename nested_class_creator<T, i>::type> inner_m;
int foo() { return inner_m.foo() };
int bar() { return inner_m.bar() };
int baz() { return inner_m.baz() };
};
*/
/*
have tried... where the unified api could be called through _manager_class
template<typename T, int i>
using _manager_class = manager_class <T, typename nested_class_creator<T, i>::type>;
template<typename T, typename outer_nested_class_t>
using _manager_class = manager_class <T, outer_nested_class_t>;
But obviously it does not work...
*/
int
main() {
manager_class <int, outer_nested_class<int, outer_nested_class<int, inner_nested_class<int>, 0x4>, 0x3>> manager_with_user_specified_configs;
// how do I do this?
//manager_class <int, 3> manager_with_simply_api;
}
这可能吗?如果可以,我该怎么做?
我很高兴使用任何版本的 C++ >= 11
注意:我知道我可以为此使用预处理器宏作为更坏的情况。如果可能的话,我宁愿找到一个解决方案,以便用户可以简单地指定一个 int 或类型。
【问题讨论】:
标签: c++ c++11 templates c++14 c++17