好的,我知道应该避免使用单例,但是很少有真正需要单例的情况。所以我的解决方案使用 CRTP(奇怪的重复模式)实现它们,如下所示:
#include <iostream>
#include <utility>
using namespace std;
template<typename T> // Singleton policy class
class Singleton
{
protected:
Singleton() = default;
~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
public:
template<typename... Args>
static T& getInstance(Args... args) // Singleton
{
// Guaranteed to be destroyed.
// Instantiated on first use.
// Thread safe in C++11
static T instance{std::forward<Args>(args)...};
return instance;
}
};
class Foo: public Singleton<Foo>
{
friend class Singleton<Foo>;
Foo()
{
cout << "Constructing instance " << this <<" of Foo" << endl;
}
Foo(int x)
{
cout << "Constructing instance " << this <<" of Foo with argument x = "\
<< x << endl;
}
~Foo()
{
cout << "Destructing instance " << this << " of Foo" << endl;
}
public:
// public
};
int main()
{
Foo& rfoo = Foo::getInstance(); // default constructible
// this should just return the instance
// instead, it constructs another instance
// because invokes an overloaded version of get_instance()
Foo& rfoo1 = Foo::getInstance(1);
// this is OK
// calls the SAME overloaded version again, instance is static
// so we get the same instance
Foo& rfoo2 = Foo::getInstance(2);
}
如您所见,我允许从具有重载/非默认构造函数的类中创建单例。但这又让我反感,因为通过使用可变参数模板化的 get_instance() 函数并通过 std::forward 传递实例参数,编译器会生成重载对于具有不同类型的每个调用,因此为每个重载返回一个新的静态实例。我想要的是通过引用返回一个以某种方式对所有可能的重载都是通用的单个实例,但无法弄清楚如何去做。任何想法如何去做?谢谢!
PS:我可以使用指针而不是引用来实现解决方案,但我更喜欢引用解决方案,因为它是线程安全的,而且在我看来更优雅。
最佳答案
对不起,我终于有时间了。你可以试试这个:
#include <iostream>
#include <utility>
#include <functional>
using namespace std;
template<typename T> // Singleton policy class
class Singleton
{
protected:
Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
virtual ~Singleton() = default;
public:
template<typename... Args>
static T& getInstance(Args... args) // Singleton
{
cout << "getInstance called" << std::endl;
//we pack our arguments in a T&() function...
//the bind is there to avoid some gcc bug
static auto onceFunction = std::bind( createInstanceInternal<Args...>, args... );
//and we apply it once...
return apply( onceFunction );
}
private:
//This method has one instance per T
//so the static reference should be initialized only once
//so the function passed in is called only the first time
static T& apply( const std::function<T&()>& function )
{
static T& instanceRef = function();
return instanceRef;
}
//Internal creation function. We have to make sure it is called only once...
template<typename... Args>
static T& createInstanceInternal(Args... args)
{
static T instance{ std::forward<Args>(args)... };
return instance;
}
};
IdeOne 链接:
编辑(线程安全和设计问题):
据我所知,这在 C++11 中应该是线程安全的。 instance 和 instanceRef 都是静态局部变量,应该只进行一次线程安全初始化。但是,根据您的编译器,C++11 线程安全初始化可能未按照标准指定的方式实现。如果是这种情况,您可以在 apply 内明确同步作为临时解决方法。在我看来,客户端代码可以在不带参数和带参数的情况下调用 getInstance 仍然令人不安。如果客户端代码使用参数调用,那么很可能它期望/需要使用给定参数初始化单例。提供不止一种初始化可能性将导致客户端代码出现意外/不自然的行为。那可不好。如果 Foo 只有一个 parameterizad ctor 应该没问题。但是,这意味着您总是必须传递一些参数才能获取实例……最后,将单例 getInstance 参数化会导致比它解决的问题更多的问题。话虽这么说,我根本无法抗拒智力挑战……:-)。
关于c++ - 单例,奇怪的重复模板模式和转发构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24964769/
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby中使用两个参数异步运行exe吗?我已经尝试过ruby命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何rubygems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
我正在使用puppet为ruby程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende
我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere
我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)