在我的TClass::foo()函数,我想调用一个T实例当且仅当T是函数类型。#include#includetemplatestructTClass{TClass(Tvalue):value(value){}Tvalue;voidfoo(){//if(valueisstd::function)//callfunction;}};intmain(){TClasst1{0};t1.foo();TClass>t2{[](){std::cout我该怎么做? 最佳答案 在C++11中,最简单的方法是通过辅助函数重新推导值:templatea
我确信一定可以使用SFINAE(可能与宏一起使用)来static_assert()任意代码不会编译。在我的代码库中有一些复杂的情况,我有一个类我想禁止使用临时对象(我相信模式是):class(constclass&&tmp)=delete;/*denycopyingfromanunnamedtemporary*/class(class&&rhs){/*allowconstructionfromnon-temporaryrvalue*/}目前,我检查了一个不需要的构造函数是否编译,但当然我必须将其注释掉以使测试再次编译!如果我能做到:static_assert(DOES_NOT_COMP
我似乎找不到将SFINAE与可变模板类一起使用的好解决方案。假设我有一个不喜欢引用的可变参数模板对象:templateclassNoRef{//ifanyofArgs...isareference,thisclasswillbreak//forexample:std::tuple...>uptrs;};还有一个方便地检查参数包是否包含引用的类:templatestructRefCheck{staticconstboolvalue=std::is_reference::value||RefCheck::value;};templatestructRefCheck{staticconstb
我正在尝试定义一个has_ostream_operatorSFINAE测试,用于检查我是否可以计算出给定的类型。我让它工作,但前提是在我对has_ostream_operator的定义中我调用operator作为一种方法而不是作为中缀运算符。换句话说,这是可行的:decltype(std::declval().operator()))>这不是:decltype(std::declval()())>下面的测试用例(也可以在http://coliru.stacked-crooked.com/a/d257d9d6e0f3f6d9看到)。请注意,我包含了void_t的定义,因为我只使用C++1
我想在C++03中检查模板参数是否为引用类型。(我们在C++11和Boost中已经有了is_reference)。我利用了SFINAE以及我们不能拥有指向引用的指针这一事实。这是我的解决方案#includetemplateclassIsReference{private:typedefcharOne;typedefstruct{chara[2];}Two;templatestaticOnetest(C*);templatestaticTwotest(...);public:enum{val=sizeof(IsReference::templatetest(0))==1};enum{re
我试图了解如何SFINAE作品,我正在尝试此代码#includestructOne{usingx=int;};structTwo{usingy=int;};template*=nullptr>voidfunc(){}template*=nullptr>voidfunc(){}/*template>*=nullptr>voidfunc(){}template>*=nullptr>voidfunc(){}*/intmain(){func();func();}评论的代码有效,但第一个没有。编译器给我错误的错误,说有一个重新定义,该模板参数扣除失败了。有人可以解释为什么会发生这种情况吗?他们俩void
使用SFINAE,has_value_int和has_value_auto两者都尝试检测类T是否有一个staticconstexpr名为value的函数.使用int参数化true_type,has_value_int效劳于演示类(class)pass和fail.使用auto参数化true_type,has_value_auto总是返回false。使用int有什么区别?并使用auto,为什么auto不工作?具体来说,为什么重载决策更喜欢match_auto(...)至match_auto(int)?#includeusingnamespacestd;//parametrizetrue_t
这是我检查类是否有成员函数的代码begin还是不是:templatestructhas_begin{structdummy{typedefvoidconst_iterator;};typedeftypenamestd::conditional::yes,T,dummy>::typeTType;typedeftypenameTType::const_iteratorIter;structfallBack{Iterbegin()const;Iterend()const;};structchecker:T,fallBack{};templatestructcht;templatestatic
我了解到SFINAE可用于确定类中是否存在成员函数。例如,以下代码可用于检查方法hello是否存在于类中。structhas_method_hello{usingyes=char[1];usingno=char[2];templatestaticconstexpryes&test(decltype(&U::hello));templatestaticconstexprno&test(...);staticconstexprboolvalue=(sizeof(yes)==sizeof(test(nullptr)));};structFoo{voidhello(){}}std::cout:
#include#includestructB{template::value>*=nullptr>voidfoo(T){std::cout::value>*=nullptr>voidfoo(T){std::cout假设我们想在派生类D中公开两个foo()重载。gcc和VisualStudio编译并按我预期的那样打印“B::foo”。但是我得到了clang的编译错误:prog.cc:22:7:error:nomatchingmemberfunctionforcallto'foo'd.foo(2);~~^~~prog.cc:14:10:note:candidatetemplateigno