c++,c++14,traits,template-meta-programming
I would just do this to only match types with a tuple member called children: template<typename S, typename T, std::size_t = std::tuple_size<decltype(T::children)>::value> S& operator<<(S& s, const T& t) { ... } And might implement the body like this: template<typename S, typename T, std::size_t... I> void print_tuple_like(S& s, const T& t,...
c++,templates,c++11,template-meta-programming,typetraits
You cannot do that with just the function type available, because default arguments are not part of the function type. The following holds: void foo(int, int); void bar(int, int = 42); static_assert(std::is_same<decltype(foo), decltype(bar)>::value, "He's wrong!"); This means you cannot say whether a function of type Func can be called with...
c++,templates,template-meta-programming
This is way overcomplicated. Here's how I would have written Concat: template <int...> class Seq; template <typename SeqA, typename SeqB> class Concat; template <int... Ints1, int... Ints2> class Concat<Seq<Ints1...>, Seq<Ints2...>> { using type = Seq<Ints1..., Ints2...>; }; Yes, std::conditional needs to evaluate all of its parameters; no short-circuiting happens. This...
c++,c++11,boost,metaprogramming,template-meta-programming
If you have a C++11 capable compiler, I find it highly unlikely that you require BOOST_DEDUCED_TYPENAME. i.e., this is located in include/boost/config/suffix.hpp: // BOOST_DEDUCED_TYPENAME workaround ------------------------------------------// // // Some compilers don't support the use of `typename' for dependent // types in deduced contexts, e.g. // // template <class T> void...
c++,c++11,variadic-templates,template-meta-programming
As you have already been hinted, the best way is to use a tuple: template<typename ...AcceptedTypes> // e.g. MyClass<T1, T2> class MyClass { std:tuple<std::vector<AcceptedTypes>...> vectors; }; This is the only way to multiply the "fields" because you cannot magically make it spell up the field names. Another important thing may...
c++,templates,template-meta-programming,crtp
I think the most straightforward way to do something like this is to dispatch to a different non-virtual function that the derived class can shadow if it so desires. For example: template <class T> struct MyHelper { size_t size() const { return sizeof(T); } void print(std::ostream &out) const { //...
c++,c++11,template-meta-programming
The logic to inverse the indices is not palatable and I could not proceed from this stage. I take it you are referring to solutions that use std::index_sequence (C++14), or the like, such as Jonathan Wakeley's', and that @Columbo's solution in the same vein would be unpalatable too, even...
c++,templates,c++11,metaprogramming,template-meta-programming
Improper usage of std::conditional std::conditonal<condition, true-type, false-type> Your problem boils down to that both the true- and false-type in std::conditional must yield a valid name, no matter which side the condition picks. Note: There's a proposed solution at the end of this post if a full explanation isn't needed. Consider...
c++,templates,wrapper,template-meta-programming,policy
This is fairly easy to do using C++11 syntax, or higher. Here's an example of implementing a Vector wrapper, that will result in the syntax that you're looking for. Use a similar approach to implement Matrix, etc. The approach combines template specialization, with template using, selecting the correct specialization that...
c++,c++11,template-meta-programming
For example, like this: namespace detail { template <int n, bool isNegative> struct factorial_impl { enum { value = n * factorial_impl<n - 1, isNegative>::value }; }; template <int n> struct factorial_impl<n, true> { enum { value = -1 }; }; template <> struct factorial_impl<0, false> { enum { value...
c++,templates,dynamic,metaprogramming,template-meta-programming
try this template <class T> void do_stuff() { std::vector<T> v; // Do stuff with v } void do_suff_dispatch(int i) { switch (i) { case 0: do_stuff<int>(); break; case 1: do_stuff<float>(); break; } } for (int i = 0; i < 2; ++i) { do_suff_dispatch(i); } ...
c++,templates,metaprogramming,template-meta-programming
You can't specialize just one function inside a class template; you have to specialize the class template as a whole. template <typename T> class Ref { void Decrement(); }; template <typename T> class Collection {}; template <typename T> class Ref<Collection<T>> { void Decrement() {} }; You can specialize a function...
c++,templates,c++11,boost,template-meta-programming
Your expression is not sufficient, as the lexical_cast function template takes everything and only reports errors via an internal static_assert. Instead test whether inserting the object into an std::ostream is valid: template <typename T, typename=void> struct IsLexCastable : std::false_type {}; // Can be extended to consider std::wostream as well for...
c++,c++11,tuples,variadic-templates,template-meta-programming
This code works correctly on clang and g++ (using C++11): http://coliru.stacked-crooked.com/a/c8071ab447e10a31 Produces a std::tuple with Max_N elements of the same type, and fills it up with the first values of the given list. If less elements in list than Max_N, fills the last elements with sentinel values. In practice, using...
c++,macros,template-meta-programming
What you are trying to achieve is called X Macro. In the case you don't want to include any files or provide element/def_vert/end_vert definitions at every expansion site, you can pass them as extra parameters to MyVertexDef macro. #define MyVertexDef(def_vert, element, end_def) \ def_vert(MyVertex) \ element(float, 3, Position, POSITION, 0)...
c++,templates,c++11,template-meta-programming,typetraits
This is a run time check semantically. This means that the code in the {} is compiled, even if the expression is always false: if(std::is_arithmetic<T>::value) { raw_string = raw_string.substr(0, found) + std::to_string(arg_head) + raw_string.substr(found + 1, raw_string.size()); } to fix this, you can do this: template<typename T> void do_arithmetic( std::string&...
c++,templates,metaprogramming,template-meta-programming,typetraits
template<template<class...>class Z> struct negate { template<class...Ts> using result=std::integral_constant<bool, !Z<Ts...>::value>; }; Filter<negate<std::is_pod>:: template result, int, char, std::string, int>; or Filter<typename negate<std::is_pod>::result, int, char, std::string, int>; depending on compiler should work. (IIRC, some compilers are quirky about this) As I find this syntax awkward, maybe take a list of tests to daisy...
c++,templates,c++14,template-meta-programming
something like this? #include <iostream> #include <string> #include <tuple> #include <typeinfo> #include <cstddef> template<class Ch, class Tr, class Tuple, std::size_t... Is> void print_tuple_impl(std::basic_ostream<Ch, Tr>& os, const Tuple & t, std::index_sequence<Is...>) { using swallow = int[]; // guaranties left to right order (void)swallow { 0, (void(os << (Is == 0 ?...
c++,templates,template-meta-programming
unsigned int foo = 5 + 7; won't be obfuscated as this falls under constant folding. and would be replaced simply with unsigned int foo = 12; at compile time. The technique is particularly useful for expressions like. uint32 a = 5; uint32 b = 7; unsigned int foo =...
c++,templates,c++11,template-meta-programming
v.template templFcn<Bool>(0); // Compiler error, Line 16 (see below) Dependent clauses need disambiguation, so it knows < is a template clause opener, not less-than....
Yes. Make the function templates and then conditionaly enable them using std::enable_if: #include <type_traits> template <class T> class A { public: template<typename U = T> typename std::enable_if<std::is_same<U,int>::value>::type has_int() {} template<typename U = T> typename std::enable_if<std::is_same<U,char>::value>::type has_char() {} }; int main() { A<int> a; a.has_int(); // OK // a.has_char(); // error...
c++,template-meta-programming,compile-time
how horrible is this and can it be improved? Somewhere between hideous and horrendous. (Some questions better left unasked.) And yes... All I want in the end is a list mapping a a string to a function. Is there a better way to create a map or should I...
c++,templates,c++11,template-meta-programming
I think it'll just be easier to have an array of functions, that you construct with a wrapper: using CallbackFn = std::function<void(void*, const uint32_t)>; template <typename T> CallbackFn make_processor(void (*func)(T*)) { return [=](void* payload, const uint32_t size){); ASSERT(payloadSize == sizeof(T)); func(static_cast<T*>(payload)); }; } That way, you can pass the processing...
c++,metaprogramming,template-meta-programming
Previously I had a boost-focused answer that I wasn't able to test. Here's something more comprehensible using a combination of template meta-programming and macros: #include <iostream> // Build a base template for the save Implementation template <typename... ARG_TYPES> struct save_impl; // Create a DoSerialize function that will recursively serialize all...
c++,templates,c++11,types,template-meta-programming
You can use partial specialization to get the right type, maybe like this: template <typename T, bool> struct ValueType { using type = T; }; template <typename T> struct ValueType<T, true> { using type = typename T::value_type; }; template <class K> struct A { using T = typename ValueType<K, std::is_class<K>::value>::type;...
d,mixins,template-meta-programming
I'm hoping somebody can come up with something cleaner, but this should do what you want: mixin template Generator(string name) { mixin("alias " ~ name ~ " = _fun;"); @property void _fun pure nothrow { //some cool stuff here } } This unfortunately injects _fun into the local namespace as...
c++,templates,c++11,template-meta-programming
So does this mean that "one template parameter" always gets choosen before "two template parameters, one default"? No. A partial specialization is used when an instantiation matches its template argument list, and when it is "more specialized" than any other partial specializations that match (which is not relevant here,...
The short-circuiting behavior of && doesn't stop the compiler from evaluating both expressions. min<a...>::value still has to be well-formed. So when a... becomes empty you end up with an instantiation of min<>, for which no specialization has been defined. You can fix this by specializing for a single parameter: template...
c++,templates,template-meta-programming
It doesn't really have to do with CRTP, but rather with the fact that for dependent-base-accessing derived code, you need to qualify things. Changing the line to std::cout<<this->protectedData<<std::endl; solved it. See accessing a base class member in derived class....
c++,dsl,template-meta-programming,expression-templates,boost-proto
Finally I find a way to make an expression terminal of a primitive array to make a minimal EDSL for vector algebra. It can suppress superfluous copy of temporary objects when initializing terminal objects of expression templates. The key to the elimination of object copy is to put a primitive...
c++,templates,c++11,template-meta-programming
First, an id-expression naming a nonstatic member function (mem_type::update in this case) can't be used as an unevaluated operand (such as the operand of decltype). §5.1.1 [expr.prim.general]/p13 (footnote omitted): An id-expression that denotes a non-static data member or non-static member function of a class can only be used: as part...
I'd say this really depends on the desired semantics (equivalently: intended use) of the trait. In some contexts, you might want to cover everthing "based" on Foo<T>, in other contexts, only Foo<T> itself is what you're after. Going by the name alone, I would probably use std::remove_cv as the wrapper....
c++,templates,gcc,clang,template-meta-programming
Every primary and partial specializations static data members must be defined separately. template <int N, int I> const int Table<N, I>::dummy = …; The only thing defined here is Table<N, I>::dummy - the primary specializations static data member. [temp.class.spec.mfunc]/11: Class template partial specialization members that are used in a way...
c++,boost,template-meta-programming
There are 2 and a half versions in this answer: based on variant<>, based on optional<> and a version that doesn't actually take the constructor arguments, but instead takes a factory calleable. This might enable more reduction of dynamic allocations (but deviates a bit from the question) Boost Variant Update...
c++,templates,c++11,template-meta-programming
This is like the posterchild for void_t. template<class ...> using void_t = void; // workaround for some compilers: // template<class...> struct voider { using type = void; }; // template<class... Args> using void_t = typename voider<Args...>::type; template<class T, class = void> struct pointer_type_or_default { using type = typename T::value_type*; };...
c++,list,templates,template-meta-programming,cons
In OP's own solution, it only works for global scope, not class scope, nor function scope. My implementation here works for all of global, class and function scope. Another advantage over OP's solution is my solution allow multiple list START_LIST/END_LIST pairs overlap, i.e. different list constructions can be interleaving. One...
c++,templates,metaprogramming,c++14,template-meta-programming
Here's a generic template to allow deferred instantiation by simply not instantiating :) template <bool B, template <typename...> class TrueTemplate, template <typename...> class FalseTemplate, typename ArgsTuple> struct LazyConditional; template <template <typename...> class TrueTemplate, template <typename...> class FalseTemplate, typename ... Args> struct LazyConditional<true, TrueTemplate, FalseTemplate, std::tuple<Args...>> { using type = TrueTemplate<Args...>;...
c++,templates,template-meta-programming,sfinae,result-of
Freshly voted into the library fundamentals TS at last week's committee meeting: template<class T> using to_string_t = decltype(std::to_string(std::declval<T>())); template<class T> using has_to_string = std::experimental::is_detected<to_string_t, T>; Then tag dispatch and/or SFINAE on has_to_string to your heart's content. You can consult the current working draft of the TS on how is_detected and...
c++,c++11,variadic-templates,template-meta-programming,compile-time
The only solution I could come up with is to use a generator for the sequence which is both O(log N) Filter while generating the sequence That said, I started with this O(log N) generator and I changed the predicate from a constexpr function to a more convenient std::integral_constant -...
c++,templates,c++14,template-meta-programming
I think the following, while still recursive, is easier: template<typename Current, size_t Next, class IndexSequence> struct exclusive_scan_index_sequence_impl { using type = Current; }; template<size_t... Current, size_t Next, size_t First, size_t... Indices> struct exclusive_scan_index_sequence_impl< index_sequence<Current...>, Next, index_sequence<First,Indices...> > : exclusive_scan_index_sequence_impl< index_sequence<Current...,Next>, Next+First, index_sequence<Indices...> > { };...
c++,templates,c++11,variadic-templates,template-meta-programming
Create a namespace to put some helpers in it, called details. In details create a type struct adl_helper{}; Create an implementation of make_vector, except its first parameter is always a template parameter called Adl. This template parameter is never named, and instances of it are passed to recursions. Implement make_vector(...
c++,templates,template-meta-programming,boost-mpl
Well, you can't get a typename from concatenating strings with template parameters, but if your intention is... I'd like to have a metafunction Get_Provider_Type::type which will return for me the type fooProvider You can simply define the type in foo: struct foo { using provider = fooProvider; }; If you...
c++,templates,scheme,template-meta-programming
Try this way. template<class T, int K> struct re; template<int H, class T> struct re <list<H, T>, H> { // the head and the subject are same value. typedef T type; }; template<int H, class T, int K> struct re <list<H, T>, K>{ typedef list<H, typename re<T, K>::type> type; };...
templates,groovy,metaprogramming,template-meta-programming
Using the second example you linked to, I can get this to (I think) work: import groovy.inspect.swingui.AstNodeToScriptVisitor String method( Closure a ) { new StringWriter().with { writer -> a.metaClass.classNode.getDeclaredMethods("doCall")[0].code.visit new AstNodeToScriptVisitor( writer ) "{${writer.toString()}}" } } c1 = {p1 + p2} c2 = '{return p1 * p2}' data = [fields:...
c++,boost,template-meta-programming
It is important to note that Boost placeholders are not an "implementation" detail of Boost MPL but actually designed for use: http://www.boost.org/doc/libs/1_58_0/libs/mpl/doc/refmanual/apply.html However the behaviour observed here seems to be expected: http://www.boost.org/doc/libs/1_57_0/libs/mpl/doc/tutorial/placeholders.html There they have an example: mpl::multiplies< mpl::plus<_1,_2>, mpl::minus<_1,_2> > So Solution seems to be to wrap the class...
c++,c++11,template-meta-programming,sfinae
You want to enable the constructor if T is convertible to A? Use std::enable_if and std::is_convertible: template < class T, class Sfinae = typename std::enable_if<std::is_convertible<T, A>::value>::type > B(T param) {} This works by applying SFINAE; if T is not convertible to A, the substitution will fail and the constructor will...
c++,templates,template-meta-programming
This: template <class ToWrap> void foo(typename wrapper_maker<ToWrap>::template wrapper<true>& wrapped) Is a non-deduced context. Specifically, the first one in the list from [temp.deduct.type]4/5: If a template parameter is used only in non-deduced contexts and is not explicitly specified, template argument deduction fails. The non-deduced contexts are: (5.1) — The nested-name-specifier of...
c++,templates,type-conversion,operator-overloading,template-meta-programming
Let's say you're working with normal classes, not templates. You have a class SomeType and you want to have an assignment operator for this class so you can assign objects of type OtherType to objects of this class. So something like this: SomeType obj1; OtherType obj2; obj1 = obj; For...
c++,templates,operator-overloading,template-meta-programming,addressof
You can use decltype and declval, with a little hackery to force an lvalue to be passed to the & operator (which is required): Start with #include <utility> and define the following helper function: template <typename T> T& as_lvalue(T&& val) { return val; } Then: using TPtr = decltype(&as_lvalue(std::declval<T>())); (live...
c++,templates,template-meta-programming
This is the magic switch problem -- how to take a (range of) run time values and turn it into a compile time constant. Start with C++1y-replaced boilerplate: template<unsigned...> struct indexes {typedef indexes type;}; template<unsigned max, unsigned... is> struct make_indexes: make_indexes<max-1, max-1, is...> {}; template<unsigned... is> struct make_indexes<0, is...>:indexes<is...> {};...
c++,c++11,template-meta-programming,fold
Until C++17 and fold expressions come along, a straightforward implementation of all_of is: // base case; actually only used for empty pack template<bool... values> struct all_of : std::true_type {}; // if first is true, check the rest template<bool... values> struct all_of<true, values...> : all_of<values...> {}; // if first is false,...
c++,templates,c++11,function-pointers,template-meta-programming
You put Return (*fn_ptr)( Params... ) in the wrong place. It's a template parameter of the partial specialization, so it goes into the template <...>. template< typename T, typename fn_ptr_t, fn_ptr_t fn_ptr > struct Fl_Callback_package; template< typename T, typename Return, typename... Params, Return (*fn_ptr)( Params... ) > struct Fl_Callback_package< T,...
c++,templates,namespaces,metaprogramming,template-meta-programming
Such a solution does not exist: A template type parameter does neither establish its own scope, nor does it have any ADL-like lookup rules. Also, you cannot pass it any arbitrary token, but you need to pass it a type. Therefore, whatever you pass it must be findable in the...
c++,templates,boost,c++14,template-meta-programming
You can do the opposite: specify types in the class declaration, and use universal initialization syntax for constructor arguments (though it won't work for explicit constructors): class XMLSignatureDocument : public ElementContainer<XMLDeclarationElement, SignatureXMLElement> { public: XMLSignatureDocument() :ElementContainer( {"<?xml version=\"1.0\" encoding=\"utf-8\"?>"}, {"<Signature xmlns=\"http://www.w3.org/2000/09/xmldsig#\"></signature>"} ) {}; }; ...
c++,c++11,lambda,template-meta-programming,trampolines
#include <utility> template <typename T, T t> struct trap; template <typename R, typename... Args, R(Base::*t)(Args...)> struct trap<R(Base::*)(Args...), t> { static R call(int s, Args... args) { try { return (get_base(s)->*t)(std::forward<Args>(args)...); } catch (...) { return std::is_integral<R>::value ? static_cast<R>(42) : static_cast<R>(3.14); } } }; Usage: table->fp_53 = &trap<decltype(&Base::f53), &Base::f53>::call; table->fp_54 =...
c++,templates,c++11,template-meta-programming,static-assert
// empty list: template<typename... Args> struct List { struct head {static_assert(sizeof...(Args) != 0, "Attempt to access the head of an empty list."); }; struct tail {static_assert(sizeof...(Args) != 0, "Attempt to access the tail of an empty list."); }; }; // non-empty list: template<typename Head, typename ...Tail> struct List<Head, Tail...> {...
c++,syntax,alias,template-meta-programming
On this line: getArgs<typename func1<int>::operator()>::Type typename func1<int>::operator() is not a type, it's a function. You need to call decltype() on a pointer to it. Use operator& to get a pointer to member: getArgs<decltype(&func1<int>::operator())>::Type ...
c++,templates,c++11,template-meta-programming,llvm-clang
Long story; short. You are actually not instantiating foo<bool> in the following expression: std::is_same<ok, foo<bool>>::value; When does implicit instantiation occur? 14.7.1 Implicit instantiation [templ.inst] 5) A class template specialization is implicitly instantiated if the class type is used in a context that requires a completely-defined object type or if the...
c++,templates,c++11,lambda,template-meta-programming
First of all, you should really learn what an SSCCE really is, especially the "complete" part. Also, short. That said, I tried to create an SSCCE which seems to reproduce your problem, see at the end of my answer. Looking at the error message you receive, it seems that your...
The problem with one-pass code is that you have to keep the state - you have to remember whether you encountered the dominating element or not. Writing a simple for loop would give you an advantage of short-circuiting when you know that the result is false. But if you want...
c++,templates,c++11,template-meta-programming,stdtuple
You can't use mem_fn to create a wrapper that calls a member function on objects of heterogeneous type, as the wrapper created by mem_fn wraps a pointer to a particular member of a particular type. The trick is to pass something with a templated function call operator that can accept...
c++,templates,template-meta-programming
typename = ... declares an unnamed template parameter. Client code could still override it, but the parameter can't be used in the function definition. This is used here because the second template parameter is used to leverage SFINAE rather than to work out a type to use in the...
c++,c++11,lambda,variadic-templates,template-meta-programming
Want defined behaviour? Add: static Func state(Func* op=0){ static Func f=*op; return f; } to your template class. First time you call it, pass a ptr to lambda. 2nd time, extract value for free. The static Func f is constructed the first time the function is called: so long as...
c++,c++14,template-meta-programming,compile-time
You guessed it. Use a pack template, and "simplify" a bit: template <typename...> struct pack {}; // To be potentially introduced in C++1Z template <typename, typename, typename=void> struct Exists_impl : std::false_type {}; template <typename R, typename... Args> struct Exists_impl<R, pack<Args...>, std::enable_if_t<std::is_same<decltype(foo(std::declval<Args>()...)), R>::value>> : std::true_type {}; template <typename R, typename... Args>...
c++,boost,c++14,template-meta-programming
Utility tools: #include <iostream> #include <tuple> #include <vector> #include <type_traits> template <typename... Ts> struct pack {}; template <typename T, typename... Ts> constexpr bool Contains = false; template <typename T, typename U, typename... Ts> constexpr bool Contains<T, U, Ts...> = Contains<T, Ts...>; template <typename T, typename... Ts> constexpr bool Contains<T, T,...
c++,boost,template-meta-programming,c-strings,boost-test
I don't think you can really support this scenario because all SFINAE techniques I can think of would run into ambiguous overloads. This is, in fact, precisely the documented limitation with Boost's has_equal_to<A,B,R> type trait: There is an issue if the operator exists only for type A and B is...
c++,templates,template-meta-programming
You're missing a typename and a template: typedef typename encapsulate_arguments< // ^^^^^^^^ Master<L>::template Slave, pack<double, int> // ^^^^^^^^ >::type EmbeddedType; Demo...
Specialisations can have template parameters themselves. Specialisations with template parameters are called partial specialisations. template<class T> struct rank { ...1 }; means rank<T> is a class, and unless otherwise specified, ...1 is the class's definition. template<class U, size_t N> struct rank<U[N]> { ...2 }; is the "otherwise specified": it means...