接口(interface):
template <class T>
class Interface{
public:
typedef T Units;
virtual T get() = 0;
};
实现 1:
class Implementation1: public Interface<float> {
public:
float get() {
return 0.0f;
}
};
实现2:
class Implementation2: public Interface<int> {
public:
int get() {
return 0;
}
};
容器(有错误):
class Container{
private:
Interface* floatGetter;
int n;
Timer::Units* array;
public:
Container(Interface* floatGetter, int n) {
this->floatGetter= floatGetter;
this->n = n;
array = new Timer::Units[n];
}
~Container() {
}
};
有关更多详细信息,我有一个模板接口(interface)和一个没有模板的接口(interface)的派生类。其他一些类采用派生类的对象,但它将对象作为接口(interface)(换句话说,依赖注入(inject))。但是这个类中接口(interface)的类型是由接口(interface)实现定义的。如何在 C++ 中实现这个想法?
编辑1:
例子:
Interface<float> myInterface1 = new Implementation1();
Interface<int> myInterface2 = new Implementation2();
Container container1 = new Container(myInterface1, 10);
Container container2 = new Container(myInterface2, 10);
我需要容器从其实现中理解接口(interface)模板参数。
最佳答案
OK,首先解释一下这里的问题。需要的是一个接口(interface),它定义了一个虚拟方法,用于获取具有模板化类型的值。由于我们要的是接口(interface),所以get方法必须是virtual的。另一方面,我们希望能够返回不同的类型,因此我们希望将其模板化。但是,虚拟方法不能被模板化,因为编译器不知道该方法的哪些实例要包含在 vtable 中。
一个解决方案是做问题中所做的事情,即模板化接口(interface)类。模板类型的一个重要属性是同一类的不同实例化是完全不同的类型。它们没有共同的基础,也不能相互转换。我们根本无法拥有 Interface<Generic>指针在常规函数中循环,调用它们的 get() 方法。考虑一下:Interface 模板类型的每个实例都有不同的 get() 方法签名。这意味着在调用该方法时,堆栈上必须发生不同的事情。如果编译器只有一个 Interface<Generic>,它怎么知道要调用哪个版本的 get() 方法(如何为函数调用准备堆栈)指针。
对于这个问题,我可以想到两个通用的解决方案。
移除所有模板mumbo-jumbo 并使get() 方法返回类型删除的对象,例如boost::variant 或boost::any。如果我在这里错了请纠正我(*),但是 boost::variant 就像一个 union 体,它会记住分配了哪种类型的 union 体,而 boost::any 就像一个 void *,但它会记住它指向的类型.此解决方案路径意味着两件事: a) 返回对象的类型将在运行时解析,操作这些类型时会有一些开销。 b) Interface 的子类将不得不管理这些类型删除对象之一,使它们更加复杂。
将模板 mumbo-jumbo 发挥到极致,并始终在模板化上下文中引用接口(interface)对象,以便编译器在这些上下文的实例化过程中生成正确的函数调用。我在下面给出了一个遵循这条路径的例子。该示例创建了一个容器,用于将不同类型的 Interface<> 对象放在一起,同时允许对它们应用模板化函数(通常将其称为“访问者”是否正确?)。请注意,在该示例中,具有不同类型参数的接口(interface)对象实际上保存在该容器类中的不同 std::list 中,因此在运行时,无需解析它们的类型。
免责声明:以下是矫枉过正......
下面是如何让“接口(interface)”模板类的容器具有不同的模板参数。我使用 std::list 来保留实例,但您可以更改它。
#include<boost/fusion/container/vector.hpp>
#include<boost/fusion/algorithm.hpp>
#include<boost/mpl/transform.hpp>
#include<boost/mpl/contains.hpp>
#include<boost/utility/enable_if.hpp>
#include<boost/type_traits/add_reference.hpp>
#include<list>
#include<algorithm>
#include <iostream>
using namespace boost;
template <class T>
class Interface{
public:
typedef T Units;
virtual T get() = 0;
};
class Implementation1: public Interface<float> {
public:
float get() {
return 0.0f;
}
};
class Implementation2: public Interface<int> {
public:
int get() {
return 5;
}
};
template<class element>
struct to_list {
typedef std::list<Interface<element> *> type;
};
template<class elementVector>
struct to_containers {
typedef typename mpl::transform<elementVector,to_list<mpl::_1> >::type type;
};
class Container{
typedef fusion::vector<int,float> AllowedTypes;
typename to_containers<AllowedTypes>::type containers;
public:
template<class type> typename enable_if<mpl::contains<AllowedTypes,type>,void>::type
/*void*/ add(Interface< type/*included in AllowedTypes*/ > & floatGetter) {
fusion::deref(fusion::find<typename to_list<type>::type >(containers))
/*<type> container*/.push_back(&floatGetter);
}
template<class functional>
void apply(functional f) {
fusion::for_each(containers,applyFunctional<functional>(f));
}
private:
template<class functional>
struct applyFunctional {
functional f;
applyFunctional(functional f): f(f){}
template<class T> void operator()(T & in) const {
std::for_each(in.begin(), in.end(),f);
}
};
};
struct printValueFunctional {
template<class element>
void operator()(Interface<element> * in) const {
std::cout<<"Hi, my value is:"<<in->get()<<"\n";
}
};
int main() {
Implementation1 impl1;
Implementation2 impl2;
Interface<float> &myInterface1 = impl1;
Interface<int> &myInterface2 = impl2;
Container container;
container.add(myInterface1);
container.add(myInterface2);
container.apply(printValueFunctional());
return 0;
}
输出是:
Hi, my value is:5
Hi, my value is:0
嗯,这对大多数应用程序来说确实是一个巨大的矫枉过正,但你要求它:)
如果你只是想要一个接口(interface),可以返回不同的东西,你也可以考虑 boost.variant。上面的示例因其使用的所有静态多态性而真正有值(value)。
编辑:David 指出了一些重要的事情,如果您出于某种原因做出其他假设,这可能是一个陷阱。这个容器并没有真正遵守项目插入的顺序。您的函数调用顺序可能不会按照插入项的顺序发生,即假设迭代将按“随机”顺序进行。
(*) 讨论了 boost::variant 和 boost::any here
关于C++ Templates 多态障碍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9089229/
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:
我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我
我有一个数组数组,想将元素附加到子数组。+=做我想做的,但我想了解为什么push不做。我期望的行为(并与+=一起工作):b=Array.new(3,[])b[0]+=["apple"]b[1]+=["orange"]b[2]+=["frog"]b=>[["苹果"],["橙子"],["Frog"]]通过推送,我将推送的元素附加到每个子数组(为什么?):a=Array.new(3,[])a[0].push("apple")a[1].push("orange")a[2].push("frog")a=>[[“苹果”、“橙子”、“Frog”]、[“苹果”、“橙子”、“Frog”]、[“苹果”、“
我使用的是遗留数据库,所以我无法控制数据模型。他们使用了很多多态链接/连接表,就像这样createtableperson(per_ident,name,...)createtableperson_links(per_ident,obj_name,obj_r_ident)createtablereport(rep_ident,name,...)其中obj_name是表名,obj_r_ident是标识符。因此链接的报告将按如下方式插入:insertintoperson(1,...)insertintoreport(1,...)insertintoreport(2,...)insertint
有没有办法让Ruby能够做这样的事情?classPlane@moved=0@x=0defx+=(v)#thisiserror@x+=v@moved+=1enddefto_s"moved#{@moved}times,currentxis#{@x}"endendplane=Plane.newplane.x+=5plane.x+=10putsplane.to_s#moved2times,currentxis15 最佳答案 您不能在Ruby中覆盖复合赋值运算符。任务在内部处理。您应该覆盖+,而不是+=。plane.a+=b与plane.a=
出于某种原因,heroku尝试要求dm-sqlite-adapter,即使它应该在这里使用Postgres。请注意,这发生在我打开任何URL时-而不是在gitpush本身期间。我构建了一个默认的Facebook应用程序。gem文件:source:gemcuttergem"foreman"gem"sinatra"gem"mogli"gem"json"gem"httparty"gem"thin"gem"data_mapper"gem"heroku"group:productiondogem"pg"gem"dm-postgres-adapter"endgroup:development,:t
我是Ruby和这个网站的新手。下面两个函数是不同的,一个在函数外修改变量,一个不修改。defm1(x)x我想确保我理解正确-当调用m1时,对str的引用被复制并传递给将其视为x的函数。运算符当调用m2时,对str的引用被复制并传递给将其视为x的函数。运算符+创建一个新字符串,赋值x=x+"4"只是将x重定向到新字符串,而原始str变量保持不变。对吧?谢谢 最佳答案 String#+::str+other_str→new_strConcatenation—ReturnsanewStringcontainingother_strconc
我正在使用PostgreSQL9.1.3(x86_64-pc-linux-gnu上的PostgreSQL9.1.3,由gcc-4.6.real(Ubuntu/Linaro4.6.1-9ubuntu3)4.6.1,64位编译)和在ubuntu11.10上运行3.2.2或3.2.1。现在,我可以使用以下命令连接PostgreSQLsupostgres输入密码我可以看到postgres=#我将以下详细信息放在我的config/database.yml中并执行“railsdb”,它工作正常。开发:adapter:postgresqlencoding:utf8reconnect:falsedat
这是我在ChefRecipe中的一blockRuby:#ifdatadirdoesn'texist,moveoverthedefaultoneif!File.exist?("/vol/postgres/data")execute"mv/var/lib/postgresql/9.1/main/vol/postgres/data"end结果是:Executingmv/var/lib/postgresql/9.1/main/vol/postgres/datamv:inter-devicemovefailed:`/var/lib/postgresql/9.1/main'to`/vol/post