小编Vuw*_*wox的帖子

C++ Singleton Instance禁用重新调用

使用Meyers单身时:

class Singleton
{
public:
    static Singleton& instance()
    {
        static Singleton instance;
        return instance;
    }

    void Hello()
    {
        std::cout <<"Hello!\n";
    }

protected:
    Singleton() = default;
    ~Singleton() {};

private:
    Singleton(Singleton const&);
    Singleton& operator=( Singleton const& );
};
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式调用实例:

Singleton::instance().Hello();
Run Code Online (Sandbox Code Playgroud)

要么

Singleton& s = Singleton::instance();
s.Hello();
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有办法阻止这个:

Singleton::instance().instance();
Run Code Online (Sandbox Code Playgroud)

如何避免调用instance()作为方法(带.)并且只支持静态调用::

有没有办法使用static_assert,模板enable_if或其他任何东西?

c++ singleton static c++11

1
推荐指数
1
解决办法
103
查看次数

如果仅使用模板,则启用模板功能

基于以下模板化的结构,用作像素访问器。

template<class T, std::size_t N>
struct PixelAccessor
{   
    T ch[N];
};

using pxUChar_C1 = PixelAccessor<unsigned char, 1>;
using pxUChar_C3 = PixelAccessor<unsigned char, 3>;
using pxUChar_C4 = PixelAccessor<unsigned char, 4>;

using pxFloat_C1 = PixelAccessor<float, 1>;
using pxFloat_C3 = PixelAccessor<float, 3>;
using pxFloat_C4 = PixelAccessor<float, 4>;

// etc. for all other types (int, short, ushort, ...)
Run Code Online (Sandbox Code Playgroud)

我做了以下函数,仅适用于3个通道的uchar和float像素。

template<typename T, typename = typename std::enable_if<std::is_same<T, pxUChar_C3>::value || std::is_same<T, pxFloat_C3>::value>::type>
bool function(Image img) {
     // where getData is uchar*, and cast to T** allow 2D …
Run Code Online (Sandbox Code Playgroud)

c++ templates c++11

1
推荐指数
1
解决办法
59
查看次数

标签 统计

c++ ×2

c++11 ×2

singleton ×1

static ×1

templates ×1