【发布时间】:2020-02-14 14:05:15
【问题描述】:
我正在尝试制作 CRTP Singleton。这里已经有几个例子了。我不确定我的有何不同或为什么无法编译。第一次尝试:
template<class Impl>
class Base
{
public:
static const Impl& getInstance();
static int foo(int x);
private:
static const Impl impl{};
};
template<class Impl> inline
const Impl& Base<Impl>::getInstance()
{
return impl;
}
template<class Impl> inline
int Base<Impl>::foo(int x)
{
return impl.foo_impl(x);
}
class Derived1 : public Base<Derived1>
{
public:
int foo_impl(int x) const;
};
int Derived1::foo_impl(int x) const
{
return x + 3;
}
int main(int argc, char** argv)
{
const Derived1& d = Derived1::getInstance();
std::cout << Derived1::foo(3) << std::endl;
return 0;
}
g++ 7.4.0 告诉我:error: in-class initialization of static data member ‘const Derived1 Base<Derived1>::impl’ of incomplete type.
嗯。那好吧。不知道为什么该类型不完整。试试:
. . .
private:
static constexpr Impl impl{};
};
现在我们在链接时失败了:undefined reference to 'Base<Derived1>::impl'
真的?!对我来说看起来已经定义并初始化了......但即使它确实链接了我有一个带有非平凡析构函数的 Derived,所以编译器会在编译时炸弹,抱怨 constexpr 中使用的非文字类型。
为什么 Derived1 不完整?我该如何构建它?
【问题讨论】: