使用模板生成纯虚基 class 方法
Use templates to generate pure virtual base class methods
这听起来可能有点奇怪,我可能不得不在某个时候重构我的代码,但我需要生成带有模板函数的纯虚拟基础 class 方法。它是否适用于 C++11(可变参数模板?)?
示例:
struct I
{
virtual void foo(int) = 0;
virtual void foo(float) = 0;
};
struct S : public I
{
template<typename T>
void foo(T t) { /*do the same symbolic stuff on t*/ }
};
int main()
{
S s;
s.foo(0);
s.foo(0.0f);
return 0;
}
出现以下错误 (clang):
main.cpp:65:7: error: variable type 'S' is an abstract class
S s;
^
main.cpp:53:18: note: unimplemented pure virtual method 'foo' in 'S'
virtual void foo(int) = 0;
^
main.cpp:54:18: note: unimplemented pure virtual method 'foo' in 'S'
virtual void foo(float) = 0;
^
1 error generated.
你不能那样做。
模板方法的签名与非模板方法不同。
而且你不能有虚拟模板方法。
你不能直接做,但是你可以使用转发器有一个共同的实现:
struct S : public I
{
private:
template<typename T>
void foo_impl(T t) { /*do the same symbolic stuff on t*/ }
public:
virtual void foo(int v) { foo_impl(v); }
virtual void foo(float v) { foo_impl(v); }
};
这听起来可能有点奇怪,我可能不得不在某个时候重构我的代码,但我需要生成带有模板函数的纯虚拟基础 class 方法。它是否适用于 C++11(可变参数模板?)?
示例:
struct I
{
virtual void foo(int) = 0;
virtual void foo(float) = 0;
};
struct S : public I
{
template<typename T>
void foo(T t) { /*do the same symbolic stuff on t*/ }
};
int main()
{
S s;
s.foo(0);
s.foo(0.0f);
return 0;
}
出现以下错误 (clang):
main.cpp:65:7: error: variable type 'S' is an abstract class
S s;
^
main.cpp:53:18: note: unimplemented pure virtual method 'foo' in 'S'
virtual void foo(int) = 0;
^
main.cpp:54:18: note: unimplemented pure virtual method 'foo' in 'S'
virtual void foo(float) = 0;
^
1 error generated.
你不能那样做。
模板方法的签名与非模板方法不同。
而且你不能有虚拟模板方法。
你不能直接做,但是你可以使用转发器有一个共同的实现:
struct S : public I
{
private:
template<typename T>
void foo_impl(T t) { /*do the same symbolic stuff on t*/ }
public:
virtual void foo(int v) { foo_impl(v); }
virtual void foo(float v) { foo_impl(v); }
};