【发布时间】:2014-06-16 17:12:38
【问题描述】:
是否可以在派生类中禁用Foo() 覆盖(通过std::enable_if 或一些增强魔法),以防T 不是特定类型,而不必为@ 编写模板特化987654323@?
加分项:如果 T 没有定义某个方法,是否可以禁用覆盖?
这是我的 SSCCE:
#include <iostream>
#include <string>
class Base
{
public:
virtual std::string Foo()
{
return "Base";
}
};
template <typename T>
class Derived : public Base
{
public:
virtual std::string Foo() override
{
return "Derived";
}
};
int main()
{
Derived<int> testInt;
std::cout << testInt.Foo() << std::endl;
Derived<float> testFloat;
std::cout << testFloat.Foo() << std::endl;//I would like this to print 'Base'
}
更新:
感谢您提供出色的解决方案,但我无法使它们适应我的真实代码。以下示例应该更好地了解我想要实现的目标:
#include <iostream>
#include <string>
class Object
{
public:
void Test()
{
std::cout << "Test" << std::endl;
}
};
class EmptyObject
{
};
class Base
{
public:
virtual std::string Foo()
{
return "Base";
}
};
template <typename T>
class Derived : public Base
{
public:
virtual std::string Foo() override
{
m_object.Test();
return "Derived";
}
private:
T m_object;
};
int main()
{
Derived<Object> testObject;
std::cout << testObject.Foo() << std::endl;
Derived<EmptyObject> testEmpty;
std::cout << testEmpty.Foo() << std::endl;
}
【问题讨论】:
-
在
C++11你可以标记函数final并且它不能被覆盖。但是,我不知道您是否可以使用虚函数来做到这一点。 -
那无济于事。我确实需要覆盖从 Base 派生的一些类中的方法(这只是一个简单的例子)
-
@user2899162 当然可以用虚函数来完成。 而且只有他们。
-
啊@Constructor,不确定我是否混淆了我的语法。很高兴知道,谢谢。
标签: c++ templates inheritance boost enable-if