如果特定的自由函数不存在,从重载集中删除模板函数的规范方法是什么。所以我有一个功能templatevoidfoo(Tt){//Dostuff}如果一个自由函数采用类型T的参数,我想从重载集中删除它,比如说bar(T)不存在。另外,如果确实存在一个自由函数,如何从重载中移除一个函数呢?那么,如果函数bar确实存在,那么删除上面的函数foo吗? 最佳答案 像这样的简单表达式可以很容易地用decltype进行SFINAE:templateautofoo(Tt)->decltype(bar(t),void()){//Dostuff}
有没有办法使用detectionidiom(或其他方法)测试一个函数是否对给定的模板参数有效,如果它由于static_assert?而失败下面的示例说明了foo的有效性(失败的返回类型计算)按预期被检测到,但是bar的有效性(失败的static_assert)不是。#include#includetemplateusingvoid_t=void;templateclassOp,class...Args>structdetector:std::false_type{};templateclassOp,class...Args>structdetector>,Op,Args...>:std
假设我们有一个模板实例Container(认为Container是一个std::vector)和一个非模板类型T,我们需要检查我们是否可以调用push_back在Container类型的对象上.下面是使用检测器习惯用法的代码:#include#include#include#include#include#include#includetemplatestructreplace{usingtype=structError;};templateclassContainer,typenameU,typenameT>structreplace,T>{usingtype=Container
假设我编写了一个名为interpolate的通用函数。它的签名是这样的:templateTinterpolate(Ta,Tb,floatc);其中a和b是要插入的值,c是[0.0,1.0]中的float。如果T定义了Toperator*(float)和Toperator+(T),我希望它以某种方式表现(线性插值)。否则,它的行为会有所不同-任何T都可用(最近邻插值)。我怎样才能实现这种行为?例如:interpolate("hello","world!",0.798);//usesnearestneighbor,asstd::stringdoesnothavethenecessaryop
我有以下模板类及其类型的(全局)变量:templatestructClassTester:publicClassT{typedefClassTtype;};ClassTester*aaa;//Noerrorhere我预计会出现编译错误,因为无法派生int,但这在VisualC++2010下编译得很好。如果删除指针,则会出现预期的编译错误(无法派生int):ClassTesterbbb;//Errorhere我想将此类用于SFINAE测试给定类型是否是可以派生自的类:templatestructCanBeDerivedFrom{templatestaticinttest(ClassTes
在这个例子中,一个函数被传递给一个隐式实例化的函数模板。//Functionthatwillbepassedasargumentintfoo(){return0;}//Functiontemplatetocallpassedfunctiontemplateintcall(Ff){returnf();}templateintcall(Ff,Aa){returnf(a);}inta=call(foo);我们可以通过为foo()添加重载来破解此代码.intfoo(inti){return0;}名称“foo”现在不明确,示例将不再编译。这可以通过显式提供函数指针类型信息来编译。int(*fun
templateusingEnable_if=typenamestd::enable_if::type;classDegree;templateconstexprinlineboolIs_Degree(){returnstd::is_base_of::value;}classDegree{public:std::size_tinDeg=0;};templateclassVertex:publicSatellite{public:explicitVertex(intnum):n(num){}private:std::size_tn;};templateclassEdge{public:/
我正在编写一个模板类,它存储一个std::function以便稍后调用它。这是简化的代码:templatestructTest{voidcall(Ttype){function(type);}std::functionfunction;};问题是这个模板不能为void类型编译,因为voidcall(voidtype)变得未定义。将它专门用于void类型并不能缓解问题,因为templatevoidTest::call(void){function();}仍然与call(TType)的声明不兼容。因此,利用C++11的新特性,我尝试了std::enable_if:typenamestd::
我有这样的代码:classBar{public:voidprint(){std::coutclassFoo{public:template::value,T>::type>voidprint(){t.print();}templatevoidprint(){std::coutfoo1;Foofoo2;foo2.print();}这段代码的目的是:如果Tt是Bar或Bar的子类,然后foo.print()推导为voidprint(){t.print();},否则推导为voidprint(){std::cout,但事情并没有像我预期的那样工作。编译器错误:"anon-typetemplat
我正在尝试编写非成员运算符函数模板,例如:#includetemplateclassMyType;templateautooperator==(MyTypeconst&l,MyTypeconst&r)->decltype(std::declval()==std::declval()){/*...*/}但是当我尝试处理l和r的长度不同时:template::type>autooperator==(MyTypeconst&l,MyTypeconst&r)->decltype(std::declval()==std::declval()){/*...*/}templateLu)>::type