【发布时间】:2021-01-05 05:42:22
【问题描述】:
我希望我的模板函数只接受从基类继承的类作为参数。我认为代码 sn-p 可以更好地解释它。
class Base
{
// Some magic
}
class Derived : public Base
{
// Even more magic
}
class Foo
{}
// Is it possible to tell template to accept only classes derived from Base?
template<class T>
do_something(T obj)
{
// Perform some dark magic incantations on obj
}
int main()
{
Foo foo;
Derived derived;
do_something<Derived>(derived); // Normal
do_something<Foo>(foo); // Compilation error if I understand templates correctly
}
【问题讨论】:
-
你会用 C++20 吗?
-
@AndyG C++ 17 我想只有
-
应该
do_something允许Base本身的实例吗?