使用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或其他任何东西?
基于以下模板化的结构,用作像素访问器。
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)