我想提供一个函数声明/定义,它根据输入参数返回正确的数据类型。这听起来就像函数模板的用途,但更具体地说,我希望函数接口(interface)看起来像:
template<class InT>
RetT getData(InT*);
在哪里,
稍微介绍一下后台应用程序。假设我有一个文本处理系统,我可以为其指定各种配置。一些配置可能是标志(即 bool 值),如 performCompact、addSpacing 等。一些配置可能是标记(即字符串文字),如 prefixToPath 、surfixToLastName 等。某些配置可能是自定义数据类型,例如 textColorMap、fontFamily 等。
我想提供一个通用函数来查询每个配置的数据,而不是每个配置一个函数。而且由于配置数据以不同的类型存储,我需要此函数根据用于查询的配置返回正确的数据类型。
选择这种设计的主要原因是为了节省维护工作。这个查询基础设施在它自己的组件中,不同的团队在他们自己的组件中处理不同的配置子集。我想尽量减少维护工作,以便在添加新配置时无需修改查询接口(interface)。
下面给出了一些示例代码。这满足了这两个要求,但是我仍然想知道是否有办法避免 Requirement2 的类模板。
#include <iostream>
using namespace std;
// In a *.hpp file in component A
template<class T>
auto getData(T* spec) {
return spec->data();
}
template<class DataT>
class Configuration {
public:
virtual DataT data() = 0;
};
// In some other components source files
class PerformCompact : Configuration<bool> {
private:
bool _data;
public:
PerformCompact(bool d):_data(d){}
bool data() override {return _data;}
};
class PrefixToPath : Configuration<string>{
private:
string _data;
public:
PrefixToPath(string d):_data(d){}
string data() override {return _data;}
};
// In one application source file
int main()
{
PerformCompact performCompact(true);
PrefixToPath prefixToPath("Some string");
auto pd = getData(&performCompact);
auto pstr = getData(&prefixToPath);
cout << pd << endl;
cout << pstr << endl;
return 0;
}
最佳答案
可以将 SFINAE 与来自 <type_traits> 的新元函数一起使用检查函数返回行中类型的条件。如果某些函数模板的条件失败,而其他函数模板没有失败,SFINAE 确保编译器继续前进并选择最佳函数模板候选者。
如果可以在编译时检查您的类型的条件,这当然有效。这个小例子检查两种类型是否可以相互赋值,然后启用返回类型。如果类型不可分配(C 与 (A,B) 的组合),则编译失败:
#include <type_traits>
#include <cassert>
class A;
class B;
class C;
class A
{
public:
void operator=(B const& b) {};
};
class B
{
public:
void operator=(A const& a) {};
};
class C {};
template<class RetT, class InT>
std::enable_if_t
<
std::is_assignable<InT,RetT>::value,
RetT
>
getData(InT*)
{
RetT result;
return result;
};
using namespace std;
int main()
{
A* Aptr = new A;
B* Bptr = new B;
C* Cptr = new C;
getData<A>(Bptr);
getData<B>(Aptr);
// Assignments not there, so the compilation fails.
getData<B>(Cptr);
getData<C>(Bptr);
getData<A>(Cptr);
getData<C>(Aptr);
delete Aptr;
Aptr = nullptr;
delete Bptr;
Bptr = nullptr;
delete Cptr;
Cptr = nullptr;
return 0;
};
您还可以使用 if constexpr如果可以使用 C++17,则在函数体中:
template<class RetT, class InT>
RetT
getData(InT*)
{
if constexpr (std::is_assignable<InT,RetT>::value)
{
RetT result;
return result;
}
else assert(false && "RetT and IntT not assignable.");
};
if constexpr在编译时评估,如果为真
RetT result;
return result;
被编译,否则 assert 语句被编译。如果您尝试将函数与 C、(A,B) 组合使用,则会出现运行时错误:
RetT getData(InT*) [with RetT = B; InT = C]: Assertion `false && "RetT and IntT not assignable."' failed.
如果你想在编译时激活断言,你可以使用static_assert .
关于c++ - C++中有没有一种设计模式可以方便地以统一的函数接口(interface)查询不同类型的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54082307/
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.
我主要使用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
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数
我知道我可以指定某些字段来使用pluck查询数据库。ids=Item.where('due_at但是我想知道,是否有一种方法可以指定我想避免从数据库查询的某些字段。某种反拔?posts=Post.where(published:true).do_not_lookup(:enormous_field) 最佳答案 Model#attribute_names应该返回列/属性数组。您可以排除其中一些并传递给pluck或select方法。像这样:posts=Post.where(published:true).select(Post.attr
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳
我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s