C++接口的模板专用化
C++ template specialization for interface
为什么编译器在运行以下代码时不选择接口模板?是否需要额外的声明/提示,或者这通常不起作用?
我只是好奇这是否真的可能。
class Interface {
public :
virtual void Method() = 0;
virtual ~Interface() { }
};
class Derived : Interface {
public :
void Method() {
cout<<"Interface method"<<endl;
}
};
template<typename T>
struct Selector {
static void Select(T& o) {
cout<<"Generic method"<<endl;
}
};
template<>
struct Selector<Interface> {
static void Select(Interface& o) {
o.Method();
}
};
int i;
Selector<int>::Select(i) // prints out "Generic method" -> ok
Derived d;
Selector<Derived>::Select(d); // prints out "Generic method" -> wrong
// should be "Interface method"
试试这个(和#include <type_traits>
):
template <typename T, typename = void>
struct Selector
{
static void Select(T & o)
{
std::cout << "Generic method" << std::endl;
}
};
template <typename T>
struct Selector<T,
typename std::enable_if<std::is_base_of<Interface, T>::value>::type>
{
static void Select(Interface & o)
{
o.Method();
}
};
事实证明,enable_if
与默认模板参数相结合可用于指导部分专业化。
编译器将选择最匹配的函数版本。采用参数确切类型的函数总是胜过需要转换的函数。在这种情况下,模板函数是完全匹配的,因为它匹配任何内容;Interface
专用化需要将参数从Derived
转换为Interface
。
这将使您能够获得所需的结果:
#include <iostream>
#include <type_traits>
using namespace std;
class Interface {
public :
virtual void Method() = 0;
virtual ~Interface() { }
};
class Derived : public Interface {
public :
void Method() {
cout<<"Interface method"<<endl;
}
};
template<typename T, typename S = void>
struct Selector {
static void Select(T& o) {
cout<<"Generic method"<<endl;
}
};
template<typename T>
struct Selector<T, typename enable_if< is_base_of<Interface, T>::value >::type> {
static void Select(Interface& o) {
o.Method();
}
};
int main()
{
int i;
Selector<int>::Select(i); // prints out "Generic method" -> ok
Derived d;
Selector<Derived>::Select(d); // prints out "Generic method" -> wrong
// should be "Interface method"
}
相关文章:
- .cpp和.h文件中的模板专用化声明
- 调用专用模板时出错"no matching function for call to [...]"
- 模板专用化(按容器):value_type
- C++核心准则 C35 对于接口类"A base class destructor should be either public and virtual, or protected and nonv
- Visual C++GC接口如何启用它以及要包含哪个库
- Windows.h与GLFW.h的接口
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 提供与TMP和SFINAE的通用接口
- 静态数据成员模板专用化的实例化点在哪里
- 为重写std::exception的库生成swig接口时出错
- 内联如何影响模块接口中的成员函数
- 特征 3 类的模板专用化
- 是具有接口专用化的子类多态的模板实例化
- 如何保证C++模板类专用化之间的接口一致?
- 静态声明专用类的接口指针数组
- C++具有特定接口的类型进行模板专用化
- 专用模板类并添加新接口
- 如何继承具有大量分区专用化接口的类
- C++接口的模板专用化
- 组织专用成员 Vector<Vector 接口的最佳方式<Type>>