【发布时间】:2014-08-05 17:59:01
【问题描述】:
我是 C++11 的新手,我正在尝试构建一个经典的接口/实现对。考虑以下示例:
#include <iostream>
#include <memory>
// Interface
class IFace {
public:
virtual ~IFace () = 0;
};
// Why must I define this concrete implementation?
inline IFace::~IFace () { }
// Implementation
class Impl : public IFace {
public:
virtual ~Impl () { }
};
int main (int argc, char ** argv) {
auto impl = std::shared_ptr<Impl> (new Impl ());
return 0;
}
如果我在接口 inline IFace::~IFace () { } 上注释掉不需要的具体析构函数,我会收到链接错误
Undefined symbols for architecture x86_64:
"IFace::~IFace()", referenced from:
Impl::~Impl() in ifac_impl.cpp.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
即使接口和实现是模板化的,我也必须这样做:
// Template IFace2
template <typename T>
class IFace2 {
public:
virtual ~IFace2 () = 0;
};
// I have to do this even if the pair is templated.
template <typename T>
inline IFace2<T>::~IFace2<T> () { }
template <typename T>
class Impl2 : public IFace2<T> {
public:
virtual ~Impl2 () { }
};
int main (int argc, char ** argv) {
auto impl = std::shared_ptr<Impl> (new Impl ());
auto impl2 = std::shared_ptr<Impl2<double> > (new Impl2<double> ());
return 0;
}
为什么?
第二个问题是“我是不是走错路了?”也就是说,对于我想做的事情,是否有更好的模式(成语?)?诚然,我试图将我用 C# 开发的概念模式融入 C++11。这是理智的吗?如果不是,那么理智的方法是什么?
【问题讨论】: