Search Results

Search found 27 results on 2 pages for 'sfinae'.

Page 1/2 | 1 2  | Next Page >

  • Why does SFINAE not apply to this?

    - by Simon Buchan
    I'm writing some simple point code while trying out Visual Studio 10 (Beta 2), and I've hit this code where I would expect SFINAE to kick in, but it seems not to: template<typename T> struct point { T x, y; point(T x, T y) : x(x), y(y) {} }; template<typename T, typename U> struct op_div { typedef decltype(T() / U()) type; }; template<typename T, typename U> point<typename op_div<T, U>::type> operator/(point<T> const& l, point<U> const& r) { return point<typename op_div<T, U>::type>(l.x / r.x, l.y / r.y); } template<typename T, typename U> point<typename op_div<T, U>::type> operator/(point<T> const& l, U const& r) { return point<typename op_div<T, U>::type>(l.x / r, l.y / r); } int main() { point<int>(0, 1) / point<float>(2, 3); } This gives error C2512: 'point<T>::point' : no appropriate default constructor available Given that it is a beta, I did a quick sanity check with the online comeau compiler, and it agrees with an identical error, so it seems this behavior is correct, but I can't see why. In this case some workarounds are to simply inline the decltype(T() / U()), to give the point class a default constructor, or to use decltype on the full result expression, but I got this error while trying to simplify an error I was getting with a version of op_div that did not require a default constructor*, so I would rather fix my understanding of C++ rather than to just do what works. Thanks! *: the original: template<typename T, typename U> struct op_div { static T t(); static U u(); typedef decltype(t() / u()) type; }; Which gives error C2784: 'point<op_div<T,U>::type> operator /(const point<T> &,const U &)' : could not deduce template argument for 'const point<T> &' from 'int', and also for the point<T> / point<U> overload.

    Read the article

  • SFINAE failing with enum template parameter

    - by zeroes00
    Can someone explain the following behaviour (I'm using Visual Studio 2010). header: #pragma once #include <boost\utility\enable_if.hpp> using boost::enable_if_c; enum WeekDay {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY}; template<WeekDay DAY> typename enable_if_c< DAY==SUNDAY, bool >::type goToWork() {return false;} template<WeekDay DAY> typename enable_if_c< DAY!=SUNDAY, bool >::type goToWork() {return true;} source: bool b = goToWork<MONDAY>(); compiler this gives error C2770: invalid explicit template argument(s) for 'enable_if_c<DAY!=6,bool>::type goToWork(void)' and error C2770: invalid explicit template argument(s) for 'enable_if_c<DAY==6,bool>::type goToWork(void)' But if I change the function template parameter from the enum type WeekDay to int, it compiles fine: template<int DAY> typename enable_if_c< DAY==SUNDAY, bool >::type goToWork() {return false;} template<int DAY> typename enable_if_c< DAY!=SUNDAY, bool >::type goToWork() {return true;} Also the normal function template specialization works fine, no surprises there: template<WeekDay DAY> bool goToWork() {return true;} template<> bool goToWork<SUNDAY>() {return false;} To make things even weirder, if I change the source file to use any other WeekDay than MONDAY or TUESDAY, i.e. bool b = goToWork<THURSDAY>(); the error changes to this: error C2440: 'specialization' : cannot convert from 'int' to 'const WeekDay' Conversion to enumeration type requires an explicit cast (static_cast, C-style cast or function-style cast)

    Read the article

  • SFINAE + sizeof = detect if expression compiles

    - by FredOverflow
    I just found out how to check if operator<< is provided for a type. template<class T> T& lvalue_of_type(); template<class T> T rvalue_of_type(); template<class T> struct is_printable { template<class U> static char test(char(*)[sizeof( lvalue_of_type<std::ostream>() << rvalue_of_type<U>() )]); template<class U> static long test(...); enum { value = 1 == sizeof test<T>(0) }; typedef boost::integral_constant<bool, value> type; }; Is this trick well-known, or have I just won the metaprogramming Nobel prize? ;) EDIT: I made the code simpler to understand and easier to adapt with two global function template declarations lvalue_of_type and rvalue_of_type.

    Read the article

  • C++11 Tidbits: access control under SFINAE conditions

    - by Paolo Carlini
    Lately I have been spending quite a bit of time on the SFINAE ("Substitution failure is not an error") features of C++, fixing and tweaking various bits of the GCC implementation. An important missing piece was the implementation of the resolution of DR 1170 which, in a nutshell, mandates that access checking is done as part of the substitution process. Consider: class C { typedef int type; }; template <class T, class = typename T::type> auto f(int) - char; template <class> auto f(...) -> char (&)[2]; static_assert (sizeof(f<C>(0)) == 2, "Ouch"); According to the resolution, the static_assert should not fire, and the snippet should compile successfully. The reason being that the first f overload must be removed from the candidate set because C::type is private to C. On the other hand, before the resolution of DR 1170, the expected behavior was for the first overload to remain in the candidate set, win over the second one, to eventually lead to an access control error (*). GCC mainline (would be 4.8) finally implements the DR, thus benefiting the many modern programming techniques heavily exploiting SFINAE, among which certainly the GNU C++ runtime library itself, which relies on it for the internals of <type_traits> and in several other places. Note that the resolution of the DR is active even in C++98 mode, not just in C++11 mode, because it turned out that the traditional behavior, as implemented in GCC, wasn't fully consistent in all the possible circumstances. (*) In practice, GCC didn't really implement this, the static_assert triggered instead.

    Read the article

  • If the address of a function can not be resolved during deduction, is it SFINAE or a compiler error?

    - by Faisal Vali
    In C++0x SFINAE rules have been simplified such that any invalid expression or type that occurs in the "immediate context" of deduction does not result in a compiler error but rather in deduction failure (SFINAE). My question is this: If I take the address of an overloaded function and it can not be resolved, is that failure in the immediate-context of deduction? (i.e is it a hard error or SFINAE if it can not be resolved)? Here is some sample code: struct X { // template T* foo(T,T); // lets not over-complicate things for now void foo(char); void foo(int); }; template struct S { template struct size_map { typedef int type; }; // here is where we take the address of a possibly overloaded function template void f(T, typename size_map::type* = 0); void f(...); }; int main() { S s; // should this cause a compiler error because 'auto T = &X::foo' is invalid? s.f(3); } Gcc 4.5 states that this is a compiler error, and clang spits out an assertion violation. Here are some more related questions of interest: Does the FCD-C++0x clearly specify what should happen here? Are the compilers wrong in rejecting this code? Does the "immediate-context" of deduction need to be defined a little better? Thanks!

    Read the article

  • SFINAE and detecting if a C++ function object returns void.

    - by Tom Swirly
    I've read the various authorities on this, include Dewhurst and yet haven't managed to get anywhere with this seemingly simple question. What I want to do is to call a C++ function object, (basically, anything you can call, a pure function or a class with ()), and return its value, if that is not void, or "true" otherwise. #include <stdio.h> struct Foo { void operator()() {} }; struct Bar { bool operator()() { return false; } }; Foo foo; Bar bar; bool baz() { return false; } void bang() {} const char* print(bool b) { printf(b ? "true, " : "false, "); } template <typename Functor> bool magicCallFunction(Functor f) { return true; // lots of template magic occurs here... } int main(int argc, char** argv) { print(magicCallFunction(foo)); print(magicCallFunction(bar)); print(magicCallFunction(baz)); print(magicCallFunction(bang)); printf("\n"); }

    Read the article

  • Multiple SFINAE rules

    - by Fred
    Hi everyone, After reading the answer to this question, I learned that SFINAE can be used to choose between two functions based on whether the class has a certain member function. It's the equivalent of the following, just that each branch in the if statement is split into an overloaded function: template<typename T> void Func(T& arg) { if(HAS_MEMBER_FUNCTION_X(T)) arg.X(); else //Do something else because T doesn't have X() } becomes template<typename T> void Func(T &arg, int_to_type<true>); //T has X() template<typename T> void Func(T &arg, int_to_type<false>); //T does not have X() I was wondering if it was possible to extend SFINAE to do multiple rules. Something that would be the equivalent of this: template<typename T> void Func(T& arg) { if(HAS_MEMBER_FUNCTION_X(T)) //See if T has a member function X arg.X(); else if(POINTER_DERIVED_FROM_CLASS_A(T)) //See if T is a pointer to a class derived from class A arg->A_Function(); else if(DERIVED_FROM_CLASS_B(T)) //See if T derives from class B arg.B_Function(); else if(IS_TEMPLATE_CLASS_C(T)) //See if T is class C<U> where U could be anything arg.C_Function(); else if(IS_POD(T)) //See if T is a POD type //Do something with a POD type else //Do something else because none of the above rules apply } Is something like this possible? Thank you.

    Read the article

  • How to determine whether a class has a particular templated member function?

    - by Aozine
    I was wondering if it's possible to extend the SFINAE approach to detecting whether a class has a certain member function (as discussed here: "Is there a Technique in C++ to know if a class has a member function of a given signature?" http://stackoverflow.com/questions/87372/is-there-a-technique-in-c-to-know-if-a-class-has-a-member-function-of-a-given-s ) to support templated member functions? E.g. to be able to detect the function foo in the following class: struct some_class { template < int _n > void foo() { } }; I thought it might be possible to do this for a particular instantiation of foo, (e.g. check to see if void foo< 5 >() is a member) as follows: template < typename _class, int _n > class foo_int_checker { template < typename _t, void (_t::*)() > struct sfinae { }; template < typename _t > static big test( sfinae< _t, &_t::foo< _n > > * ); template < typename _t > static small test( ... ); public: enum { value = sizeof( test< _class >( 0 ) ) == sizeof( big ) }; }; Then do foo_int_checker< some_class, 5 >::value to check whether some_class has the member void foo< 5 >(). However on MSVC++ 2008 this always returns false while g++ gives the following syntax errors at the line test( sfinae< _t, &_t::foo< _n > > ); test.cpp:24: error: missing `>' to terminate the template argument list test.cpp:24: error: template argument 2 is invalid test.cpp:24: error: expected unqualified-id before '<' token test.cpp:24: error: expected `,' or `...' before '<' token test.cpp:24: error: ISO C++ forbids declaration of `parameter' with no type Both seem to fail because I'm trying to get the address of a template function instantiation from a type that is itself a template parameter. Does anyone know whether this is possible or if it's disallowed by the standard for some reason? EDIT: It seems that I missed out the ::template syntax to get g++ to compile the above code correctly. If I change the bit where I get the address of the function to &_t::template foo< _n > then the program compiles, but I get the same behaviour as MSVC++ (value is always set to false). If I comment out the ... overload of test to force the compiler to pick the other one, I get the following compiler error in g++: test.cpp: In instantiation of `foo_int_checker<A, 5>': test.cpp:40: instantiated from here test.cpp:32: error: invalid use of undefined type `class foo_int_checker<A, 5>' test.cpp:17: error: declaration of `class foo_int_checker<A, 5>' test.cpp:32: error: enumerator value for `value' not integer constant where line 32 is the enum { value = sizeof( test< _class >( 0 ) ) == sizeof( big ) }; line. Unfortunately this doesn't seem to help me diagnose the problem :(. MSVC++ gives a similar nondescript error: error C2770: invalid explicit template argument(s) for 'clarity::meta::big checker<_checked_type>::test(checker<_checked_type>::sfinae<_t,&_t::template foo<5>> *)' on the same line. What's strange is that if I get the address from a specific class and not a template parameter (i.e. rather than &_t::template foo< _n > I do &some_class::template foo< _n >) then I get the correct result, but then my checker class is limited to checking a single class (some_class) for the function. Also, if I do the following: template < typename _t, void (_t::*_f)() > void f0() { } template < typename _t > void f1() { f0< _t, &_t::template foo< 5 > >(); } and call f1< some_class >() then I DON'T get a compile error on &_t::template foo< 5 >. This suggests that the problem only arises when getting the address of a templated member function from a type that is itself a template parameter while in a SFINAE context. Argh!

    Read the article

  • Why this works (Templates, SFINAE). C++

    - by atch
    Hi guys, reffering to yesterday's post, this woke me up this morning. Why this actually works? As long as the fnc test is concerned this fnc has no body so how can perform anything? Why and how this works? I'm REALLY interested to see your answers. template<typename T> class IsClassT { private: typedef char One; typedef struct { char a[2]; } Two; template<typename C> static One test(int C::*); //NO BODY HERE template<typename C> static Two test(…); //NOR HERE public: enum { Yes = sizeof(IsClassT<T>::test<T>(0)) == 1 }; enum { No = !Yes }; }; Thanks in advance with help to understand this very interesting fenomena.

    Read the article

  • Why do you sometimes need to write <typename T> instead of just <T> ?

    - by StackedCrooked
    I was reading the Wikipedia article on SFINAE and encountered following code sample: struct Test { typedef int Type; }; template < typename T > void f( typename T::Type ) {} // definition #1 template < typename T > void f( T ) {} // definition #2 void foo() { f< Test > ( 10 ); //call #1 f< int > ( 10 ); //call #2 without error thanks to SFINAE } Now I've actually written code like this before, and somehow intuitively I knew that I needed to type "typename T" instead of just "T". However, it would be nice to know the actual logic behind it. Anyone care to explain?

    Read the article

  • Detect if class has overloaded function fails on Comeau compiler

    - by Frank
    Hi Everyone, I'm trying to use SFINAE to detect if a class has an overloaded member function that takes a certain type. The code I have seems to work correctly in Visual Studio and GCC, but does not compile using the Comeau online compiler. Here is the code I'm using: #include <stdio.h> //Comeau doesnt' have boost, so define our own enable_if_c template<bool value> struct enable_if_c { typedef void type; }; template<> struct enable_if_c< false > {}; //Class that has the overloaded member function class TestClass { public: void Func(float value) { printf( "%f\n", value ); } void Func(int value) { printf( "%i\n", value ); } }; //Struct to detect if TestClass has an overloaded member function for type T template<typename T> struct HasFunc { template<typename U, void (TestClass::*)( U )> struct SFINAE {}; template<typename U> static char Test(SFINAE<U, &TestClass::Func>*); template<typename U> static int Test(...); static const bool Has = sizeof(Test<T>(0)) == sizeof(char); }; //Use enable_if_c to only allow the function call if TestClass has a valid overload for T template<typename T> typename enable_if_c<HasFunc<T>::Has>::type CallFunc(TestClass &test, T value) { test.Func( value ); } int main() { float value1 = 0.0f; int value2 = 0; TestClass testClass; CallFunc( testClass, value1 ); //Should call TestClass::Func( float ) CallFunc( testClass, value2 ); //Should call TestClass::Func( int ) } The error message is: no instance of function template "CallFunc" matches the argument list. It seems that HasFunc::Has is false for int and float when it should be true. Is this a bug in the Comeau compiler? Am I doing something that's not standard? And if so, what do I need to do to fix it?

    Read the article

  • Is there a way to know if std::chrono::monotonic_clock is defined?

    - by Vicente Botet Escriba
    C++0X N3092 states that monotonic_clock is optional. 20.10.5.2 Class monotonic_clock [time.clock.monotonic] 1 Objects of class monotonic_clock represent clocks for which values of time_point never decrease as physical time advances. monotonic_clock may be a synonym for system_clock if system_clock::is_monotonic is true. ** 2 The class monotonic_clock is conditionally supported.** Is there a way using SFINAE or another technique to define a traits class that states if monotonic_clock is defined? struct is_monotonic_clock_defined; If yes, how? If not, shouldn't the standard define macro that gives this information at preprocessing time?

    Read the article

  • Declare module name of classes for logging

    - by Space_C0wb0y
    I currently am adding some features to our logging-library. One of these is the possibility to declare a module-name for a class that automatically gets preprended to any log-messages writing from within that class. However, if no module-name is provided, nothing is prepended. Currently I am using a trait-class that has a static function that returns the name. template< class T > struct ModuleNameTrait { static std::string Value() { return ""; } }; template< > struct ModuleNameTrait< Foo > { static std::string Value() { return "Foo"; } }; This class can be defined using a helper-macro. The drawback is, that the module-name has to be declared outside of the class. I would like this to be possible within the class. Also, I want to be able to remove all logging-code using a preprocessor directive. I know that using SFINAE one can check if a template argument has a certain member, but since other people, that are not as friendly with templates as I am, will have to maintain the code, I am looking for a much simpler solution. If there is none, I will stick with the traits approach. Thanks in advance!

    Read the article

  • Partial template specialization: matching on properties of specialized template parameter

    - by Kenzo
    template <typename X, typename Y> class A {}; enum Property {P1,P2}; template <Property P> class B {}; class C {}; Is there any way to define a partial specialization of A such that A<C, B<P1> > would be A's normal template, but A<C, B<P2> > would be the specialization? Replacing the Y template parameter by a template template parameter would be nice, but is there a way to partially specialize it based on P then? template <typename X, template <Property P> typename Y> class A {}; // template <typename X> class A<X,template<> Y<P2> > {}; <-- not valid Is there a way by adding traits to a specialization template<> B<P2> and then using SFINAE in A?

    Read the article

  • Problem with incomplete type while trying to detect existence of a member function

    - by abir
    I was trying to detect existence of a member function for a class where the function tries to use an incomplete type. The typedef is struct foo; typedef std::allocator<foo> foo_alloc; The detection code is struct has_alloc { template<typename U,U x> struct dummy; template<typename U> static char check(dummy<void* (U::*)(std::size_t),&U::allocate>*); template<typename U> static char (&check(...))[2]; const static bool value = (sizeof(check<foo_alloc>(0)) == 1); }; So far I was using incomplete type foo with std::allocator without any error on VS2008. However when I replaced it with nearly an identical implementation as template<typename T> struct allocator { T* allocate(std::size_t n) { return (T*)operator new (sizeof(T)*n); } }; it gives an error saying that as T is incomplete type it has problem instantiating allocator<foo> because allocate uses sizeof. GCC 4.5 with std::allocator also gives the error, so it seems during detection process the class need to be completely instantiated, even when I am not using that function at all. What I was looking for is void* allocate(std::size_t) which is different from T* allocate(std::size_t). My questions are (I have three questions, but as they are correlated , so I thought it is better not to create three separate questions). Why MS std::allocator doesn't check for incomplete type foo while instantiating? Are they following any trick which can be implemented ? Why the compiler need to instantiate allocator<T> to check the existence of the function when sizeof is not used as sfinae mechanism to remove/add allocate in the overload resolutions set? It should be noted that, if I remove the generic implementation of allocate leaving the declaration only, and specialized it for foo afterwards such as struct foo{}; template< struct allocator { foo* allocate(std::size_t n) { return (foo*)operator new (sizeof(foo)*n); } }; after struct has_alloc it compiles in GCC 4.5 while gives error in VS2008 as allocator<T> is already instantiated and explicit specialization for allocator<foo> already defined. Is it legal to use nested types for an std::allocator of incomplete type such as typedef foo_alloc::pointer foo_pointer; ? Though it is practically working for me, I suspect the nested types such as pointer may depend on completeness of type it takes. It will be good to know if there is any possible way to typedef such types as foo_pointer where the type pointer depends on completeness of foo. NOTE : As the code is not copy paste from editor, it may have some syntax error. Will correct it if I find any. Also the codes (such as allocator) are not complete implementation, I simplified and typed only the portion which I think useful for this particular problem.

    Read the article

  • How to detect whether there is a specific member variable in class?

    - by Kirill V. Lyadvinsky
    For creating algorithm template function I need to know whether x or X (and y or Y) in class that is template argument. It may by useful when using my function for MFC CPoint class or GDI+ PointF class or some others. All of them use different x in them. My solution could be reduces to the following code: template<int> struct TT {typedef int type;}; template<class P> bool Check_x(P p, typename TT<sizeof(&P::x)>::type b = 0) { return true; } template<class P> bool Check_x(P p, typename TT<sizeof(&P::X)>::type b = 0) { return false; } struct P1 {int x; }; struct P2 {float X; }; // it also could be struct P3 {unknown_type X; }; int main() { P1 p1 = {1}; P2 p2 = {1}; Check_x(p1); // must return true Check_x(p2); // must return false return 0; } But it does not compile in Visual Studio, while compiling in the GNU C++. With Visual Studio I could use the following template: template<class P> bool Check_x(P p, typename TT<&P::x==&P::x>::type b = 0) { return true; } template<class P> bool Check_x(P p, typename TT<&P::X==&P::X>::type b = 0) { return false; } But it does not compile in GNU C++. Is there universal solution? UPD: Structures P1 and P2 here are only for example. There are could be any classes with unknown members.

    Read the article

  • boost::enable_if class template method

    - by aaa
    I got class with template methods that looks at this: struct undefined {}; template<typename T> struct is_undefined : mpl::false_ {}; template<> struct is_undefined<undefined> : mpl::true_ {}; template<class C> struct foo { template<class F, class V> typename boost::disable_if<is_undefined<C> >::type apply(const F &f, const V &variables) { } template<class F, class V> typename boost::enable_if<is_undefined<C> >::type apply(const F &f, const V &variables) { } }; apparently, both templates are instantiated, resulting in compile time error. is instantiation of template methods different from instantiation of free functions? I have fixed this differently, but I would like to know what is up. Thank you

    Read the article

  • Possible for C++ template to check for a function's existence?

    - by andy
    Is it possible to write a C++ template that changes behavior depending on if a certain member function is defined on a class? Here's a simple example of what I would want to write: template<class T> std::string optionalToString(T* obj) { if (FUNCTION_EXISTS(T->toString)) return obj->toString(); else return "toString not defined"; } So if class T has "toString" defined then it uses it, otherwise it doesn't. The magical part that I don't know how to do is the "FUNCTION_EXISTS" part.

    Read the article

  • C++ - checking if a class has a certain method at compile time

    - by jetwolf
    Here's a question for the C++ gurus out there. Is there a way to check at compile time where a type has a certain method, and do one thing if it does, and another thing if it doesn't? Basically, I have a template function template <typename T> void function(T t); and I it to behave a certain way if T has a method g(), and another way if it doesn't. Perhaps there is something that can be used together with boost's enable_if? Something like this: template <typename T> enable_if<has_method<T, g, void ()>, void>::type function(T t) { // Superior implementation calling t.g() } template <typename T> disable_if<has_method<T, g, void ()>, void>::type function(T t) { // Inferior implementation in the case where T doesn't have a method g() } "has_method" would be something that preferably checks both that T has a method named 'g', and that the method has the correct signature (in this case, void ()). Any ideas?

    Read the article

  • can these be made unambiguous

    - by R Samuel Klatchko
    I'm trying to create a set of overloaded templates for arrays/pointers where one template will be used when the compiler knows the size of the array and the other template will be used when it doesn't: template <typename T, size_t SZ> void moo(T (&arr)[SZ]) { ... } template <typename T> void moo(T *ptr) { ... } The problem is that when the compiler knows the size of the array, the overloads are ambiguous and the compile fails. Is there some way to resolve the ambiguity (perhaps via SFINAE) or is this just not possible.

    Read the article

  • can these templates be made unambiguous

    - by R Samuel Klatchko
    I'm trying to create a set of overloaded templates for arrays/pointers where one template will be used when the compiler knows the size of the array and the other template will be used when it doesn't: template <typename T, size_t SZ> void moo(T (&arr)[SZ]) { ... } template <typename T> void moo(T *ptr) { ... } The problem is that when the compiler knows the size of the array, the overloads are ambiguous and the compile fails. Is there some way to resolve the ambiguity (perhaps via SFINAE) or is this just not possible.

    Read the article

  • Template or function arguments as implementation details in doxygen?

    - by Vincent
    In doxygen is there any common way to specify that some C++ template parameters of function parameters are implementation details and should not be specified by the user ? For example, a template parameter used as recursion level counter in metaprogramming technique or a SFINAE parameter in a function ? For example : /// \brief Do something /// \tparam MyFlag A flag... /// \tparam Limit Recursion limit /// \tparam Current Recursion level counter. SHOULD NOT BE EXPLICITELY SPECIFIED !!! template<bool MyFlag, unsigned int Limit, unsigned int Current = 0> myFunction(); Is there any doxygen normalized option equivalent to "SHOULD NOT BE EXPLICITELY SPECIFIED !!!" ?

    Read the article

  • Visual C++ 2010, rvalue reference bug?

    - by Sergey Shandar
    Is it a bug in Visual C++ 2010 or right behaviour? template<class T> T f(T const &r) { return r; } template<class T> T f(T &&r) { static_assert(false, "no way"); return r; } int main() { int y = 4; f(y); } I thought, the function f(T &&) should never be called but it's called with T = int &. The output: main.cpp(10): error C2338: no way main.cpp(17) : see reference to function template instantiation 'T f<int&>(T)' being compiled with [ T=int & ] Update 1 Do you know any C++x0 compiler as a reference? I've tried comeau online test-drive but could not compile r-value reference. Update 2 Workaround (using SFINAE): #include <boost/utility/enable_if.hpp> #include <boost/type_traits/is_reference.hpp> template<class T> T f(T &r) { return r; } template<class T> typename ::boost::disable_if< ::boost::is_reference<T>, T>::type f(T &&r) { static_assert(false, "no way"); return r; } int main() { int y = 4; f(y); // f(5); // generates "no way" error, as expected. }

    Read the article

  • c++ class member functions instatiated by traits

    - by Jive Dadson
    I am reluctant to say I can't figure this out, but I can't figure this out. I've googled and searched stackoverflow, and come up empty. The abstract, and possibly overly vague form of the question is, how can I use the traits-pattern to instantiate non-virtual member functions? The question came up while modernizing a set of multivariate function optimizers that I wrote more than 10 years ago. The optimizers all operate by selecting a straight-line path through the parameter space away from the current best point (the "update"), then finding a better point on that line (the "line search"), then testing for the "done" condition, and if not done, iterating. There are different methods for doing the update, the line-search, and conceivably for the done test, and other things. Mix and match. Different update formulae require different state-variable data. For example, the LMQN update requires a vector, and the BFGS update requires a matrix. If evaluating gradients is cheap, the line-search should do so. If not, it should use function evaluations only. Some methods require more accurate line-searches than others. Those are just some examples. The original version instantiates several of the combinations by means of virtual functions. Some traits are selected by setting mode bits that are tested at runtime. Yuck. It would be trivial to define the traits with #define's and the member functions with #ifdef's and macros. But that's so twenty years ago. It bugs me that I cannot figure out a whiz-bang modern way. If there were only one trait that varied, I could use the curiously recurring template pattern. But I see no way to extend that to arbitrary combinations of traits. I tried doing it using boost::enable_if, etc.. The specialized state info was easy. I managed to get the functions done, but only by resorting to non-friend external functions that have the this-pointer as a parameter. I never even figured out how to make the functions friends, much less member functions. The compiler (vc++ 2008) always complained that things didn't match. I would yell, "SFINAE, you moron!" but the moron is probably me. Perhaps tag-dispatch is the key. I haven't gotten very deeply into that. Surely it's possible, right? If so, what is best practice?

    Read the article

  • C++ class member functions instantiated by traits

    - by Jive Dadson
    I am reluctant to say I can't figure this out, but I can't figure this out. I've googled and searched Stack Overflow, and come up empty. The abstract, and possibly overly vague form of the question is, how can I use the traits-pattern to instantiate non-virtual member functions? The question came up while modernizing a set of multivariate function optimizers that I wrote more than 10 years ago. The optimizers all operate by selecting a straight-line path through the parameter space away from the current best point (the "update"), then finding a better point on that line (the "line search"), then testing for the "done" condition, and if not done, iterating. There are different methods for doing the update, the line-search, and conceivably for the done test, and other things. Mix and match. Different update formulae require different state-variable data. For example, the LMQN update requires a vector, and the BFGS update requires a matrix. If evaluating gradients is cheap, the line-search should do so. If not, it should use function evaluations only. Some methods require more accurate line-searches than others. Those are just some examples. The original version instantiates several of the combinations by means of virtual functions. Some traits are selected by setting mode bits that are tested at runtime. Yuck. It would be trivial to define the traits with #define's and the member functions with #ifdef's and macros. But that's so twenty years ago. It bugs me that I cannot figure out a whiz-bang modern way. If there were only one trait that varied, I could use the curiously recurring template pattern. But I see no way to extend that to arbitrary combinations of traits. I tried doing it using boost::enable_if, etc.. The specialized state information was easy. I managed to get the functions done, but only by resorting to non-friend external functions that have the this-pointer as a parameter. I never even figured out how to make the functions friends, much less member functions. The compiler (VC++ 2008) always complained that things didn't match. I would yell, "SFINAE, you moron!" but the moron is probably me. Perhaps tag-dispatch is the key. I haven't gotten very deeply into that. Surely it's possible, right? If so, what is best practice?

    Read the article

1 2  | Next Page >