问题描述
我尝试实现此类的以下行为/语法/用法:
I try to achieve the following behavior/syntax/usage of this class:
Data1 dataType1;
Data2 dataType2;
int intType;
float floatType;
dataType1.method( intType );
dataType1.method( floatType );
dataType2.method( intType );
dataType2.method( floatType );
我的方法是:
struct CDataBase
{
template< typename T > virtual void method( T type ) = 0;
};
struct CData1 : CDataBase
{
template< typename T > void method( T type ) {}
};
struct CData2 : CDataBase
{
template< typename T > void method( T type ) {}
};
但是虚拟模板方法是不可能的。也不需要一个实际的基类,但我必须确保一些类得到一个(模板)'method()'实现。
However virtual template methods aren't possible. Also there is no need for an actual base class, However I have to ensure that some classes got a (template) 'method()' implemented.
如何强制一个非模板化的类/结构来覆盖模板方法?
How do I force a non-templated class/struct to override a template method?
编辑:
这是我的实际布局:
This is my actual layout:
struct Data0
{
int someVar;
template< class T >
void decode( T& type )
{
type.set( someVar );
}
};
编辑:
在当前版本的C ++(11)behavoir我试图实现是不可能的。除此之外,我应该重新编码这部分,以避免这个问题。
in the current version of C++ (11) the behavoir I try to achieve isn't possible. In addition to that, I should really recode this part to avoid this problem. However I accept the only answer given, thanks for you affort.
推荐答案
检查特定函数实现的基本思想是什么?模板参数类型,是尝试实例化这些的函数指针。如果函数指针初始化无法解决,编译器会报错。
The basic idea to check for specific functions implemented of a given template parameter type, is to try instantiate function pointers of these. The compiler will complain, if the function pointer initializations cannot be resolved.
下面是一些示例代码来说明原理:
Here's some sample code to illustrate the principle:
template<typename T>
void check_has_foo_function() {
void (T::*check)(int, double) = &T::foo;
(void)check;
}
struct A {
void foo(int, double) {};
};
struct B {
void bar(int, double) {};
};
template<typename CheckedClass>
struct Client {
void doSomething() {
check_has_foo_function<CheckedClass>();
CheckedClass x;
x.foo(5,3.1415);
}
};
int main() {
Client<A> clientA;
clientA.doSomething();
// Uncomment the following lines to see the compilation fails
// Client<B> clientB;
// clientB.doSomething();
return 0;
}
注意调用 check_has_foo_function< CheckedClass> );
函数将被完全优化,并且对运行时性能没有任何影响。
Note the call to the check_has_foo_function<CheckedClass>();
function will be completely optimized out, and doesn't have any impact on runtime performance.
(例如使用预处理器宏生成检查)。我已在GitHub上发布了使用这些技术的。
Based upon this, further abstractions could be provided (e.g. to generate checks using preprocessor macros). I have published a little experimental framework on GitHub that uses these techniques.
这篇关于在非模板类中强制模板方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!