【发布时间】:2021-05-29 19:18:08
【问题描述】:
是否可以(并且这是一个好主意)根据其元素的类型有条件地为某些容器类 (template<typename ThingType> class Container) 定义方法?在阅读了std::enable_if 之后,我首先认为这是可能的,但现在我不确定我是否理解。
以下是我的尝试(点击here 在ideone 上运行)。如果std::is_base_of<ThingBase, ThingType>::value 是false,则不会定义p 的返回类型。我认为编译器只会实例化一个没有该方法的类的对象。但事实证明它无法编译。
还有其他工具可以完成这项工作吗?或者我应该写两个类似Container 的类,根据ThingType 是什么而有不同的行为?或者,这可能是一份专业化的工作。
#include <iostream>
#include <type_traits>
#include <vector>
class ThingBase {
public:
virtual void printHi() = 0;
};
class Thing : public ThingBase
{
void printHi(){
std::cout << "hi\n";
}
};
template<typename ThingType>
class Container{
private:
std::vector<ThingType> m_things;
public:
typename std::enable_if<std::is_base_of<ThingBase, ThingType>::value>::type p()
{
m_things[0].printHi();
};
};
int main() {
//Container<Thing> stuff; // works!
Container<int> stuff; // doesn't work :(
return 0;
}
编辑:
编译器的错误信息是
prog.cpp: In instantiation of ‘class Container<int>’:
prog.cpp:36:17: required from here
prog.cpp:26:78: error: no type named ‘type’ in ‘struct std::enable_if<false, void>’
typename std::enable_if<std::is_base_of<ThingBase, ThingType>::value>::type p()
@StoryTeller - Unslander Monica我不打算重载这个方法。我希望最终用户只要它可用就可以使用它。这些p 方法中只有一个,并且应该只需要一个(相对简单的)签名。
【问题讨论】:
-
通常最好在此处添加编译器错误消息。
-
您寻求定义的方法是否意味着重载?会有多个
p吗?这个会有一个独特的签名吗? -
你仅限于 C++11 吗? C++20 有
requires可以方便地禁用不需要的方法。 -
@HolyBlackCat 听起来很棒,但我最好坚持使用 c++11
-
对于“如何做标题中的问题”,请参阅C++ templates: conditionally enabled member function - Stack Overflow(尽管正如下面的答案指出的那样,在这种情况下没有必要)
标签: c++ c++11 templates inheritance