C++复杂类型的单一方法的模板专用化
C++ template specialization for a single method for complex types
我有一个抽象类和子类,如下所示:
class MyAbstractClass {
public:
virtual bool shouldDoIt() = 0;
}
template <class T> class MyClass : public MyAbstractClass {
public:
bool shouldDoIt() { return state; }
private: // assume there are appropriate accessors for these private fields
bool state;
T val;
}
这种shouldDoIt()
实现适用于大多数类型。但是如果T
恰好是一个std::vector<std::shared_ptr<MyClass<X>>>
,其中X
可以是任何类型的,那么我希望实现是这样的:
bool shouldDoIt() {
if(state) return true;
for(auto &member : val) {
if(member->state) return true;
}
return false;
}
如果它是一个std::unordered_map<X, std::shared_ptr<MyClass<Y>>
,其中X
和Y
可以是任何类型的,我想要这个实现:
bool shouldDoIt() {
if(state) return true;
for(auto &member : val) {
if(member.second->state) return true;
}
return false;
}
我怎样才能专门为这些类型实现 shouldDoIt((?我正在使用Visual Studio 2015。
有几个选项可以执行此操作,我会选择哪一个取决于我希望这种特殊行为可自定义的程度。根据您在此处显示的内容,我可能会使用重载函数:
template <class T>
class MyClass : public MyAbstractClass {
public:
bool shouldDoIt() {
if (state) return true;
return specializedShouldDoIt(val);
}
private:
template <class U>
static bool specializedShouldDoIt(U&) { return false; }
template <class X>
static bool specializedShouldDoIt(
std::vector<std::shared_ptr<MyClass<X>>> &val) {
// your loop is equivalent to std::any_of
return std::any_of(val.begin(), val.end(), [](auto &member) {
return member->state;
});
}
template <class X, class Y>
static bool specializedShouldDoIt(
std::unordered_map<X, std::shared_ptr<MyClass<Y>>> &val) {
return std::any_of(val.begin(), val.end(), [](auto &member) {
return member.second->state;
});
}
};
我
可能考虑的另一种选择是使用外部帮助程序类,以便我可以使用部分专用化:
template <class T>
struct PerformShouldDoIt
{
static bool shouldDoIt(bool state, T&) { return state; }
};
template <class X>
struct PerformShouldDoIt<std::vector<std::shared_ptr<MyClass<X>>>>
{
static bool shouldDoIt(bool state,
std::vector<std::shared_ptr<MyClass<X>>>& val) {
return std::any_of(val.begin(), val.end(), [](auto &member) {
return member->state;
});
}
};
// Similarly for whatever you wanted to specialize for
...
template <class T>
class MyClass : public MyAbstractClass {
public:
bool shouldDoIt() {
return PerformShouldDoIt<T>::shouldDoIt(state, val);
}
};
相关文章:
- .cpp和.h文件中的模板专用化声明
- 调用专用模板时出错"no matching function for call to [...]"
- 模板专用化(按容器):value_type
- 静态数据成员模板专用化的实例化点在哪里
- 特征 3 类的模板专用化
- Visual Studio 2017 不允许我创建 C++ 专用模板
- 字符串化递归的"std::vector<std::vector<...>>"而不使用部分模板函数专用化
- CRTP 单一实例不完整类型或非文本类型
- 具有常量引用参数的函数模板专用化
- 使用其他模板的模板专用化
- 使用专用显卡进行 OpenGL 渲染时帧速率较低
- 嵌套模板显式专用化
- 如何检查模板专用化是否是基本模板的子类?
- C++:部分模板专用化用例
- 通过依赖类型使用非类型模板参数的单类型模板参数类模板的部分专用化
- 使用对象的基类部分模板专用化对对象进行哈希处理::哈希
- 在 C++20 中是否不再允许在 std 中对程序定义类型的函数模板进行专用化?
- 为什么依赖模板类型在部分专用化中不可推导?
- C++复杂类型的单一方法的模板专用化
- 类模板:为什么我不能将单一方法专用于空类型?