问题描述:C++17介绍std::invocable,这很适合检测类型...是否可以使用给定的参数调用。但是,对于仿函数的任何参数是否有办法做到这一点(因为标准库的现有特征的组合已经允许检测函数、函数指针、函数引用、成员函数......)?换句话说,如何实现下面的类型特征?templatestructis_functor{staticconstexprboolvalue=/*usingF::operator()inderivedclassworks*/;};使用示例:#include#includestructclass0{voidf();voidg();};structclass1{
如果涉及模板别名的替换失败(例如缺少成员类型名的模板别名,如下面的代码片段所示),是否应该触发错误?Clang和gcc似乎不同意这一点://sometypesstructbar{};structfoo{typedefvoidmember_type;};//templatealiastemplateusingmember=typenameT::member_type;templatevoidbaz(...){}//onlyworksforgcc,clangfailswith:notypenamed'member_type'//in'bar'templatevoidbaz(member*)
假设我有这个程序structA{templatestaticautofun()->typenameT::type{}};structC{//doh!Iforgottoaddatypedeffortype!};intmain(){A::fun();return0;}Liveexample出于各种原因,我可能需要auto说明符,但上面的程序会产生以下错误:prog.cpp:13:12:error:nomatchingfunctionforcallto‘A::fun()’A::fun();虽然确实如此,但并不是特别有用。很明显,在这个例子中我忘记了提供一个C::type,但是你可以看到在更大
我正在尝试通过enable_if在显式和隐式转换构造函数之间切换。我的代码目前看起来像#include#includeenumclassenabled{};templateusingenable_if_t=typenamestd::enable_if::type;templateusingdisable_if_t=typenamestd::enable_if::type;templatestructSStruct{staticconstexprstd::intmax_ta=A;};templatestructSCheckEnable:std::integral_constant{};t
在C++17中,我们有std::void_t,这让SFINAE看起来更漂亮:templatestd::void_tfoo(){/*stuff*/}只有T::prop存在,模板函数才会存在。如果T::prop存在,模板函数foo()将等同于:templatevoidfoo(){/*stuff*/}否则,代码相当于根本没有声明foo()。对于标准库中的其他类型,std::void_t是否有任何泛化,例如:templateusinggeneric_t=T;以便下面的代码有效?templatestd::generic_tfoo(){/*stuff*/}相当于templateintfoo(){/
我试图检测成员函数baz()的存在在模板参数中:templatestructImplementsBaz:publicstd::false_type{};templatestructImplementsBaz:publicstd::true_type{};但它总是产生错误:structFoo{};structBar{voidbaz(){}};std::cout::value::value使用declval不过,调用该方法确实有效:templatestructImplementsBaz().baz())>:publicstd::true_type{};当然,现在这个只能检测一个baz具有0
下面的代码正确地检查类型T是否有方法sort。但是,当我通过将decltype(&U::sort,...)更改为decltype(U::sort,...)(符号&被移除),则代码始终返回false。为什么?为什么名字本身就不够用?&是什么意思?#include#includetemplateclasshas_sort{templatestaticautocheck(bool)->decltype(&U::sort,std::true_type());//(*)templatestaticstd::false_typecheck(...);public:usingtype=decltyp
我有一个Container类,它包含一些对象,这些对象的类型可以派生自某些基类(TypeA、TypeB等)的任意组合.).Container的基类具有返回指向所包含对象的指针的虚方法;如果包含的对象不是从预期的类派生的,这些应该返回nullptr。我想根据Container的模板参数有选择地覆盖基础方法。我尝试如下使用SFINAE,但它无法编译。我想避免为每种可能的组合专门化Container,因为可能有很多组合。#include#includeusingnamespacestd;classTypeA{};classTypeB{};classTypeAB:publicTypeA,pub
我环顾四周,但无法找到解决我的具体问题的方法。我有代码:templatetypenamestd::enable_if::value||std::is_enum::value,std::string>::typeconvertToString(constTargument){returnstd::to_string(argument);}std::stringconvertToString(std::stringstring);代码应该做什么:对任何数字类型(int、float、double和ENum)使用模板版本,对其他任何类型使用std::string版本。代码本身编译得很好,但是当
这个问题在这里已经有了答案:Isitpossibletodetermineifatypeisascopedenumerationtype?(2个答案)关闭4年前。当且仅当传入的类型T是类枚举时,如何实现其值成员为true的类型特征?虽然我知道例如+T{};如果T是一个枚举会工作,如果它是一个枚举类则会失败,到目前为止我找不到将它用于SFINAE的方法。