模板类中的不可复制静态 const 成员类

noncopyable static const member class in template class

本文关键字:可复制 静态 const 成员类      更新时间:2023-10-16

我有一个不可复制的(继承自boost::noncopyable)类,我将其用作自定义命名空间。另外,我还有另一个类,它使用前一个类,如下所示:

#include <boost/utility.hpp>
#include <cmath>
template< typename F >
struct custom_namespace
    : boost::noncopyable
{
    F sqrt_of_half(F const & x) const
    {
        using std::sqrt;
        return sqrt(x / F(2.0L));
    }
    // ... maybe others are not so dummy const/constexpr methods
};
template< typename F >
class custom_namespace_user
{
    static
    ::custom_namespace< F > const custom_namespace_;
public :
    F poisson() const
    {
        return custom_namespace_.sqrt_of_half(M_PI);
    }
    static
    F square_diagonal(F const & a)
    {
        return a * custom_namespace_.sqrt_of_half(1.0L);
    }
};
template< typename F >
::custom_namespace< F > const custom_namespace_user< F >::custom_namespace_();

此代码会导致下一个错误(即使没有实例化):

错误:在类"custom_namespace_user"中没有声明"const custom_namespace custom_namespace_user::custom_namespace_()"成员函数

下一种方法是不合法的:

template< typename F >
::custom_namespace< F > const custom_namespace_user< F >::custom_namespace_ = ::custom_namespace< F >();

我应该怎么做才能声明这两个类(第一个是第二个不可复制的静态 const 成员类)?这是无所事事的吗?

您的代码被解析为函数声明,而不是对象定义。

解决方案是去掉括号:

template< typename F > ::custom_namespace< F > const custom_namespace_user< F >::custom_namespace_;