FAQ Database Discussion Community


VS2015: Variadic template specialization

c++,templates,c++11,c++14,visual-studio-2015
This code #include <iostream> #include <type_traits> template<typename Head, typename... Tail> struct Is_Admitted { constexpr static bool value = Is_Admitted<Head>::value && Is_Admitted<Tail...>::value; }; template<> template<typename T> struct Is_Admitted<T> : public std::false_type{}; template<> struct Is_Admitted<int> : public std::true_type{}; template<> struct Is_Admitted<double> : public std::true_type{}; int main() { std::cout << Is_Admitted<int,...

function && qualifier behaviour

c++,c++14,rvalue-reference
I'm confused by the following code: struct test { void f() & { std::cout << "&" << std::endl; } void f() const& { std::cout << "const&" << std::endl; } void f() && { std::cout << "&&" << std::endl; } void f() const&& { std::cout << "const&&" << std::endl; } void...

Enabling C++14 in clang in Visual Studio

c++,c++14
I've installed clang 3.7 and I'm using it with visual studio. When I try to compile: auto f() { return 2; } I'm getting error saying that this is future from C++14. I've tried to pass: -std=c++14 as compiler arguments but then I'm getting error: Error 1 error : unknown...

Getting nth variadic argument value (not type)

c++,arguments,variadic-templates,c++14
Ignore the missing perfect forwarding. (Assume arguments are perfectly forwarded in the real implementation.) // Base case: no args template<typename TF> void forEach2Args(TF) { } // Recursive case: some args template<typename TF, typename... Ts> void forEach2Args(TF mFn, Ts... mXs) { mFn(getNth<0>(mXs...), getNth<1>(mXs...)); forEach2Args(mFn, getAllAfter<2>(mXs...)); } int main() { int result{0};...

QtWidget Disable Margin for overlay widget

c++,qt,c++14,qwidget
My situation: I have a grid layout with n*n widgets inside. Additionally I place an overlay widget in the grid with position 0,0 and span n,n. Evertyhing fine with this, but there is a weird margin and I don't know what causes it... Has anyone an idea how i can...

Custom deleter specifications for std::unique_ptr

c++,c++11,c++14,unique-ptr
I am reading Josuttis` C++ standard library. I could not find the reasoning for the (2) and (3) comments on following example: D d; //instance of the deleter type(1) unique_ptr<int,D> p1(new int, D()); //D must be MoveConstructible(2) unique_ptr<int,D> p2(new int, d); //D must be CopyConstructible(3) What are the reasons for...

Unordered map in shared_ptr SIGSEGV

c++,lambda,threadpool,shared-ptr,c++14
I'm building server for speech recognizer. I'm using thread pooling to serve clients. I needed to create unordered map to save instance of recognizer for each client. So I create this_ std::shared_ptr<std::unordered_map<int ,SOnlineSpeechRecognizerI *>> user_recognizers; std::mutex rec_mutex; So on client connection I create instance of recognizer and I need to...

Fallback to copy constructor not working?

c++,c++11,copy-constructor,c++14,move-semantics
I thought that when I delete the move constructor in B then the following code will still compile fine since it should still take the copy constructor to construct B objects. Why does the compiler now complain. Without the =delete it did not and called the copy constructor anyway since...

I want to perfect forward variadic arguments except for a specific type

c++,shared-ptr,smart-pointers,c++14,perfect-forwarding
I have the following #include <iostream> #include <memory> template<typename _type> class handle { using ptr = std::shared_ptr<_type>; using pptr = std::shared_ptr<ptr>; public: handle(handle<_type> const & other) : mData(make_pptr(*(other.mData))) {} handle(_type && data) : mData(make_pptr(std::move(data))) {} private: pptr mData; template<typename ..._args> constexpr auto make_ptr(_args && ...args) { return std::make_shared<_type>(std::forward<_args>(args)...); }...

Delay a member variables type definition till another class inherits from it

c++,templates,c++14,crtp,stdtuple
I am trying to declare an member variable type to be something that a deriving class controls- without transferring the type as an template. #include <tuple> #include <iostream> #include <ostream> using namespace std; template<class DERIVED_TYPE> struct haveChildren { const std::tuple<int, DERIVED_TYPE::innerContext > myChildren; haveChildren(int a, char b) : myChildren(5, DERIVED_TYPE::innerContext{...

Why does this program compile fine in C++14 but not in a C++11 compiler?

c++,c++11,reference,c++14,list-initialization
I recently tested the simple following program on an online compiler. See live demo here. It compiles fine & gives the expected output but when I tested it on Dev C++ IDE it fails during the compilation. Here is my program: #include <iostream> class Test { int s=9; public: int...

Define virtual function to be pure in special cases of templated class

c++,c++14,template-specialization,pure-virtual
I am trying to define a templated base class that defines a virtual interface to be overriden by the user. In some cases it would make sense to have a default implementation of this method but that isn't true for all type parameters. Consider this: template<typename T> struct supplier {...

How to use Google Protobuf Map in C++?

c++,hashmap,protocol-buffers,c++14
I am attempting to use the new protobuf Map functionality in C++. The following was done on Ubuntu 14.04 with gcc 4.9.2 C++14 and protobuf 3.0.0-alpha-4: Message definition: message TestMap { map<string,uint64> map1 = 1; } Then, I tried to compile the following example program: auto test = debug::TestMap::default_instance(); auto...

User-defined literals without underscore

c++,c++11,c++14,user-defined-literals
According to cppreference it is possible to define a literal using CSomeClass operator ""s(const char* literal, size_t size); Now after reading the paragraph I think it should be also possible to define CSomeClass operator ""r(const char* literal, size_t size); (note the r ud-suffix instead of s) Overloading s just gives...

'auto' not allowed in function prototype with Clang

c++,auto,c++14,clang++
Using Clang 3.5, 3.6, or 3.7, with the flag std=c++1y the following code does not compile : #include <iostream> auto foo(auto bar) { return bar; } int main() { std::cout << foo(5.0f) << std::endl; } The error given is : error: 'auto' not allowed in function prototype I do not...

Creating an uninitialized array of items which have default constructors?

c++,arrays,initialization,c++14,default-constructor
Given a class Foo which has some value-initializing default constructor: class Foo { private: uint32_t x; public: constexpr Foo() : x { 3 } {} // ... and some other constructors }; I need to allocate an array of these Foo's. I don't want the array's elements' default constructors to...

C++ chrono library on Raspberry Pi

c++,raspberry-pi,c++14,chrono
On a Raspberry Pi 2, I need to call a php file on a regular basis, typically every 100ms. I found this c++ code which looks like it does what I need and a test version of it compiles and runs fine using CodeBlock on Windows. I've updated the wheezy...

Why does Clang++ compiler fail to compile the following variadic template code?

c++,c++14,clang++
#include <string> #include <iostream> #include <tuple> #include <utility> template<typename... T> struct test { using args_type = std::tuple<T...>; args_type x; template<std::size_t... I> void callme(std::index_sequence<I...>) { int _[] = {(std::get<I>(x).std::tuple_element<I, args_type>::type::~type(), true)...}; } }; int main() { } The error message is clang-3.7 -std=gnu++1y -Wc++14-extensions test.cpp test.cpp:15:56: error: expected ')' int _[]...

How to write a range-v3 action for random_shuffle?

c++,algorithm,c++14,range-v3
Using the range-v3 library (by @EricNiebler), makes writing algorithmic code much more compact, e.g. here's how to generate a bunch of random numbers: #include <range/v3/all.hpp> #include <iostream> #include <vector> int main() { using namespace ranges; auto const N = 10; std::vector<int> v; v.reserve(N); v |= action::push_back(view::iota(0, N)); random_shuffle(v); copy(v, ostream_iterator<>(std::cout,...

std::make_unique, anonymous namespace and ODR

c++,gcc,c++14,odr,onedefinitionrule
Please consider the following testcase (reduced from LLVM source): //% cat foo1.cpp #include <memory> namespace { class A { int i; }; } class G { std::unique_ptr<A> foo() const; }; std::unique_ptr<A> G::foo() const { return std::make_unique<A>(); } and //% cat foo2.cpp #include <memory> namespace { class A { bool...

What is the best way to find the position of the last occurrence for a specific item? [duplicate]

c++,c++11,c++14
This question already has an answer here: Is there an STL algorithm to find the last instance of a value in a sequence? 2 answers Something like this but inverse: int pos = find(v.begin(), v.end(), item) - v.begin(); ...

static_assert dependent on non-type template parameter (different behavior on gcc and clang)

c++,templates,language-lawyer,c++14,dependent-name
template <int answer> struct Hitchhiker { static_assert(sizeof(answer) != sizeof(answer), "Invalid answer"); }; template <> struct Hitchhiker<42> {}; While trying to disable general template instantiation with static_assert I discovered that the above code in clang generates the assert error even when the template is not instantiated, while gcc generates the assert...

can memcpy for std::aligned_storage?

c++,c++14,memcpy,object-lifetime
std::aligned_storage::type is POD type. POD type can memcpy. However, What happens if placement new non-trivially-copyable type to std::aligned_storage? Can it memcpy that std::aligned_storage? non-trivially-copyable type(non-POD type) can NOT memcpy, Behavior is undefined. If std::aligned_storage memcpy non-trivially-copyable type, is it also undefined behavior? #include <new> #include <type_traits> #include <cstring> #include <iostream>...

For a data member, is there any difference between dynamically allocating this variable(or not) if the containing object is already in dynamic memory?

c++,design,stl,smart-pointers,c++14
I'm starting with the assumption that, generally, it is a good idea to allocate small objects in the stack, and big objects in dynamic memory. Another assumption is that I'm possibly confused while trying to learn about memory, STL containers and smart pointers. Consider the following example, where I have...

Constexpr compound assignment operator in clang and gcc

c++,c++11,c++14,constexpr
I have the following code: main.cpp #include <cstdint> #include <type_traits> enum class FooEnum : uint8_t{ Foo1 = 0, Foo2 = 1 }; constexpr uint32_t& operator|= (uint32_t& lhs, FooEnum rhs) { return lhs |= 1u << static_cast<uint8_t>(rhs); } int main() { uint32_t bar{0}; bar|=FooEnum::Foo1; } So essentially, the |= operator is...

Does std::unordered_map

c++,c++11,c++14
This is a continuation of this question c++ function ptr in unorderer_map, compile time error I was trying to use std::function instead function pointer, and I can insert function only if the functions are static. otherwise I will get following error main.cpp:15:11: error: no matching member function for call to...

Dynamically construct tuple from vector [duplicate]

c++,c++11,c++14
This question already has an answer here: c++ : convert vector to tuple 3 answers I've got an interesting problem where I need to dynamically create a tuple from a vector where the number of type parameters of tuple equals the length of the vector. vector<int> v1 = {1,2,3};...

Accessing deduced method calls with auto keyword from header file

c++,c++14,auto
Take the following class: BasicOperations.h template<typename T1> class BasicOperations { private: T1 num; public: template<typename T1, typename T2> BasicOperations() : num(0) {} template<typename T1, typename T2> auto addition(T1 num1, T2 num2) -> decltype(T1 + T2) const { return num1 + num2; } } I have begun using auto and from...

C++: std::equal segmentation fault with my container

c++,std,c++14
I'm implementing a container like std::vector, with the aim of learning C++ and its idioms. With the purpose of overloading the operator ==, i first wrote my own version: bool operator==(const Vector& other) const{ if (_size == other._size) { for (int i = 0; i < _size; i++) if (!(_elements[i]...

Using std::vector<> and std::shared_ptr<> should cause error

c++,c++11,g++,c++14
Here is my code of what I am doing : #include <iostream> #include <vector> #include <memory> using namespace std; int main() { vector<int> ar = {1}; shared_ptr<int> sp(&ar[0]); cout<<*sp<<endl; // ---- [1] ar[0] = 10; cout<<*sp<<endl; // ---- [2] ar.clear(); cout<<*sp<<endl; // ---- [3] return 0; } The output is...

Is it definitely illegal to refer to a reserved name?

c++,c++11,language-lawyer,c++14
On the std-proposals list, the following code was given: #include <vector> #include <algorithm> void foo(const std::vector<int> &v) { #ifndef _ALGORITHM std::for_each(v.begin(), v.end(), [](int i){std::cout << i; } #endif } Let's ignore, for the purposes of this question, why that code was given and why it was written that way (as...

How to write a generic forwarding lambda in C++14?

c++,lambda,c++14,perfect-forwarding
How do I write a generic forwarding lambda in C++14? Try #1 [](auto&& x) { return x; } Inside the function body, x is an lvalue, so this doesn't work. Try #2 [](auto&& x) { return std::forward<decltype(x)>(x); } This properly forwards references inside the lambda, but it will always return...

What's the cleanest way to make (or fake) a template parameter, for a C++ generic lambda, that isn't tied to a substantial argument of the lambda?

c++,templates,lambda,c++14
I'm interested in writing a lambda function that will, among other things, call std::make_unique. To call std::make_unique I need a typename, but it would seem that in order to directly pass the typename into the lambda function, I would have to make the lambda variable a template: struct SpecialThing {...

There is a way in gcc to get a warning when a constexpr can't be evaluated at compile time?

gcc,g++,c++14,constexpr
I'm using gcc 5.1.0 (c++14) and I was trying with constexpr. Is very annoying to verify if the constexpr I've implemented are evaluated at compile time. I couldn't find any flag for get a warning about that situation. Here is an example: example.cpp ----------------------------------------- #include <stdlib.h> const char pruVar[] =...

Finding all keys that correspond to same value in std::unordered_map

c++,c++11,stl,c++14
I have an unordered_map looking like this: std::unordered_map<int, std::string> theMap2 = {{1,"a"}, {2,"b"}, {3,"c"}, {4,"a"}}; I want to find all the keys that have same value lets say 1. Any suggestions beside the obvious way: std::vector<int> arrKeys; std::string value = "a"; for (const auto& element : theMap) if (element.secont ==...

The destructor for the class member `B`, why is it invoked in the snippet below?

c++,language-lawyer,c++14,delete-operator
From §5.3.5[expr.delete]/1, I can understand that the destructor for the object *a is not invoked in the snippet below. But I didn't understand why is the destructor for the class member B invoked in this case, as can be seen in this live example. #include <iostream> class A { public:...

Odd behaviour of final on a virtual function

c++,final,c++14,undefined-reference
I've encountered a strange case when the final keyword is added to a virtual function declaration, with its definition on a separate .cpp file. Consider the following example: IClass.hpp class IClass //COM-like base interface { protected: virtual ~IClass(){} //derived classes override this public: virtual void release() final; }; dllmain.cpp (shared...

Why passing constexpr object by const reference works, but by value doesn't compile

c++,c++11,c++14,constexpr
I have the code below, that basically maps an std::integer_sequence<> into an std::array<> at compile time: #include <iostream> #include <utility> #include <array> template<int...Is> constexpr auto make_array(const std::integer_sequence<int, Is...>& param) // this works */ // constexpr auto make_array(std::integer_sequence<int, Is...> param) // doesn't compile { return std::array<int, sizeof...(Is)> {Is...}; } int main()...

Returning iterator from constant member function

c++,c++11,g++,c++14
In the following code why the return type of foo::func is vector<int>::const_iterator and not vector<int>::iterator though I am returning an object of vector<int>::iterator. #include <iostream> #include <vector> #include <algorithm> using namespace std; class foo { private: vector<int> ar; public: foo() { ar.resize(10); iota(ar.begin(), ar.end(), 1); } auto func() const {...

Remove duplicate template typename entry when inheriting

c++,templates,boost,c++14,template-meta-programming
I have a template class I inherit from(From now on referenced as parent). The template class initializes an fusion list member variable containing classes and constructers specified in the child class. template<typename... ITEM_TYPES> using List = boost::fusion::list<ITEM_TYPES...>; template<typename... CHILDREN_TYPES> class ElementContainer { protected: const List<CHILDREN_TYPES...> children; public: ElementContainer(CHILDREN_TYPES&&... args) :...

Return type of decltype when applied to ternary(?:) expression

c++,c++11,c++14
When I look into a code snippet for a possible implementation of std::common_type template <class ...T> struct common_type; template <class T> struct common_type<T> { typedef decay_t<T> type; }; template <class T, class U> struct common_type<T, U> { typedef decay_t<decltype(true ? declval<T>() : declval<U>())> type; }; template <class T, class U,...

Can't understand the declaration #3 in the Example of [basic.link]/6 C++14

c++,declaration,language-lawyer,c++14,extern
[basic.link]/6 The name of a function declared in block scope and the name of a variable declared by a block scope extern declaration have linkage. If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace...

Avoiding to defer “child” object construction with `operator<<`

c++,constructor,operator-overloading,variadic-templates,c++14
Let's say I have a container object that stores an std::vector of polymorphic children. struct Child { Child(Parent& mParent) { /* ... */ } virtual ~Child() { } }; class Parent { private: std::vector<std::unique_ptr<Child>> children; template<typename T, typename... TArgs> auto& mkChild(TArgs&&... mArgs) { // `static_assert` that `T` is derived from...

Contradictory results between GCC and clang related to [basic.link]/7 in the C++ Standard

c++,c++11,language-lawyer,c++14,linkage
This snippet compiles in clang, namespace A { void f() { void g(); g(); } } void A::g() { } but GCC only accepts the code if g is defined inside the namespace A as follows: namespace A { void f() { void g(); g(); } void g() {} }...

Is It Possible to Use a `constexpr` Template Variable as the Default for a Formal Template Argument

c++,c++14
Using clang 3.6.0, I am unable to compile the following code example. #include <type_traits> template <typename T> constexpr bool IS_SCALAR = ::std::is_scalar<T>::value; template <typename T, bool = IS_SCALAR<T>> struct Class_Breaks { }; template <typename T, bool = ::std::is_scalar<T>::value> struct Class_Works { }; void function() { Class_Breaks<int> break_error; Class_Breaks<int, IS_SCALAR<int>> breaks_ok;...

Table pass by value [duplicate]

c++,c++14
This question already has an answer here: C++ sending array to function by value, not by reference 3 answers Is it possible to pass raw table to function by value? I believe that it's impossible, but I'm looking for official sources to confirm that. I know how to pass...

__has_cpp_attribute not a 'function-like' macro?

c++,gcc,macros,c++14
I am attempting to introduce the [[deprecated]] attribute into my codebase. However, not all the compilers I am required to support have support for this syntax yet (the various method used by different compilers before standardization are described in the attribute standardization proposal N2761). Thus, I am attempting to conditionally...

Difference between “explicit” and “implicit” invocation of operator ()

c++,c++11,inheritance,c++14
Is there a clause in standard describing the following difference between a ways to call operator () from base classes? #include <iostream> #include <type_traits> #include <cstdlib> #include <cassert> template< typename visitor, typename ...visitors > struct composite_visitor : std::decay_t< visitor > , composite_visitor< visitors... > { //using std::decay_t< visitor >::operator ();...

How to know that the loop was breaked early? [closed]

c++,c++11,c99,c++14
for(int i=0; i<len_arr; i++) if(arr[i] == some_num){ printf("The idx of %d is: %d\n", some_num, i); break; } if(i == len_arr) printf("Number not found.\n"); This doesn't work. Because that i can't be accessed outside the loop. I have thought of two ways to achieve what effect I want. But my question...

Choose between template function and auto type deduction

c++,templates,auto,c++14,c++1z
I have a generic question about template functions versus auto type deduction for functions. For years, we have have been able to write template function : template <class T> T add(T a,T b){ return a+b; } There is a TS for using auto for function's parameters deduction auto add(auto a,auto...

In whats case should use auto type?

c++,lambda,auto,c++14,std-function
I have some questions regarding when use auto Explicit, it is not more clear despite the context? Cases that are better be explicit instead of auto? And with lambda functions use auto how these auto f = [](auto v, auto x) {}; //or std::function<void(auto v, auto x)> f; Thanks......

Is this code standard compliant or not?

c++,c++11,language-lawyer,c++14,c++98
So the code is class A { public: int i; A(){ i = 5; } }; class B : public A { public: void someFunc(); }; class C { A myObj; public: void func(){ B* foo = reinterpret_cast<B*>(&myObj); foo->someFunc(); } }; Assuming that classes will stay as they are and...

How to pass std::bind as universal reference type?

c++,c++11,c++14,perfect-forwarding,stdbind
As I understand it, std::bind perfectly forwards both the callable object it wraps and the arguments to that callable object; the std::bind return object is itself movable and/or copyable, depending on whether the callable object and its arguments are movable and/or copyable; a std::bind return object may be nested, in...

What is a trivial function?

c++,language-lawyer,c++14
[basic.def.odr]/3 makes a reference to the term "nontrivial function", whose definition I couldn't find in the Standard (N4140). [basic.def.odr]/3 A variable x whose name appears as a potentially-evaluated expression ex is odr-used by ex unless applying the lvalue-to-rvalue conversion (4.1) to x yields a constant expression (5.19) that does not...

Forwarding a non-type argument causes different behaviour on Variable Template

c++,c++14,template-specialization,variable-templates
This seems to be another "who's doing it well?" question since gcc 6.0.0 and clang 3.7.0 behaves different. Let's suppose we have a variable template which takes a const char * as non template argument and is specialized for a given pointer: constexpr char INSTANCE_NAME[]{"FOO"}; struct Struct{ void function() const...

I don't understand how the template function gets to be a friend of the class A::X::Y in the example in [namespace.memdef]/3 in C++14

c++,templates,language-lawyer,c++14,friend
Consider the following code from the example in [namespace.memdef]/3 in C++14: // Assume f and g have not yet been declared. void h(int); template <class T> void f2(T); namespace A { class X { friend void f(X); // A::f(X) is a friend class Y { friend void g(); // A::g...

Copy constructor with pointers to own class [closed]

c++,c++11,c++14
Assume we have a class like this: class C { public: C() {} virtual ~C() noexcept { if (c) { delete c; } } protected: int a; float b; C* c; } How would you properly implement the copy and move constructors? Normally you would just invoke the copy constructor...

Using `reinterpret_cast` on an enum class - valid or undefined behavior?

c++,language-lawyer,c++14,reinterpret-cast,enum-class
#include <iostream> #include <cassert> #include <type_traits> template<typename T> using Underlying = std::underlying_type_t<T>; enum class ETest : int { Zero = 0, One = 1, Two = 2 }; template<typename T> auto& castEnum(T& mX) noexcept { // `static_cast` does not compile // return static_cast<Underlying<T>&>(mX); return reinterpret_cast<Underlying<T>&>(mX); } int main() { auto...

Is there a C++ new declaration like in C#

c++,c++11,c++14
I wondered if there was a new declaration like in C# for C++ C# allows you to do this and it just neatens up the code a bit: FuncCall( new Foo() { Bar = "sausage", Boo = 4 } ); It's just I thought this was a bit sloppy in...

Custom range for boost::range library

c++,c++11,boost,c++14,boost-range
I’m writing filter and map algorithms using boost::range library: template <class Range> struct Converter { Converter(const Range& p_range) : m_range(p_range) {} template<class OutContainer> operator OutContainer() const { return {m_range.begin(), m_range.end()}; } private: Range m_range; }; template<class Range> Converter<Range> convert(const Range& p_range) { return {p_range}; } template<class Range, class Fun> auto...

Where in the Standard does it say that a member alias-declaration can be used as if it was a static member?

c++,alias,language-lawyer,c++14
Consider the following snippet: #include <iostream> struct A { int i; using Int = int; }; int main() { std::cout << sizeof(A::Int) << '\n'; } It compiles and executes normally in clang and GCC. I know this looks obvious, but I couldn't find anything in the Standard (C++14) supporting the...

GCC rejects a simple-declaration with an enum-base; clang accepts it — which is correct?

c++,c++11,enums,language-lawyer,c++14
GCC 4.9.2 doesn't compile this snippet, but clang 3.5.0 does. Which one is correct? enum F : int { x, y, z}; int F; enum F:int f = F::x; GCC output : main.cpp:3:12: error: expected ';' or '{' before 'f' enum F:int f = F::x; ^ main.cpp:3:12: error: expected class-key...

Why does std::shared_ptr = std::unique_ptr compile, while std::shared_ptr = std::unique_ptr does not?

c++,stl,g++,c++14
I explored this topic in Coliru with the following input command: g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out The test can be found here, but I have posted the code below. I used int in my example, as it's a basic type. #include <iostream> #include <memory> struct Foo{...

Will there be standardization of scope guard/scope exit idioms?

c++,c++14,c++1z,scopeguard
Running a lambda on scope exit seems like such a basic thing, I would expect it to be standardized. Things like unique_ptr are better, when they apply, but I find there is an endless supply of "one-off" destructors are needed, especially when leveraging C-style libraries. Does anyone know if this...

Algorithm for [inclusive/exclusive]_scan in parallel proposal N3554

c++,algorithm,parallel-processing,c++14
Proposal N3554 (A Parallel Algorithms Library) for C++14, proposes (among other things), what seem to be parallel versions of the current std::partial_sum, e.g.: template< class ExecutionPolicy, class InputIterator, class OutputIterator, class BinaryOperation> OutputIterator inclusive_scan( ExecutionPolicy &&exec, InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op); With the explanation Effects: For each...

C++ Regex: non-greedy match

c++,regex,c++11,c++14,regex-greedy
I'm currently trying to make a regex which matches URL parameters and extracts them. For example, if I got the following parameters string ?param1=someValue&param2=someOtherValue, std::regex_match should extract the following contents: param1 some_content param2 some_other_content After trying different regex patterns, I finally built one corresponding to what I want: std::regex("(?:[\\?&]([^=&]+)=([^=&]+))*"). If...

C++14 warning: too many template headers for variable (should be 0)

c++,language-lawyer,c++14,template-specialization,variable-templates
While experimenting with the recent g++-5 compiler, I wrote below statement in a file: template<T> T a; template<> int a = 1; Which results in: warning: too many template headers for a (should be 0) Also effectively, it doesn't really specialize a<int>. e.g. template<typename T> T a; template<> int a...

Scope and Default Arguments in Template Declarations in C++ : Clarifying Standardese

c++,templates,language-lawyer,c++14
I was reading through the C++14 standard's section on templates in an attempt to improve my understanding of the subject, and stumbled across this particular rule: § 14.1 12 A template-parameter shall not be given default arguments by two different declarations in the same scope. [Example: template<class T = int>...

Uniform initialization in return statement and explicit conversion operator to bool

c++,c++11,c++14
I tried to force explicit conversion in return statement by means of using of uniform initialization syntax as it is in following: #include <iostream> #include <cstdlib> struct A { explicit operator bool () const { return false; } }; bool f() { return {A{}}; // error: no viable conversion from...

Can a forwarding reference be aliased with an alias template?

c++,templates,alias,c++14,forwarding-reference
This is a continuation of my previous question: Can an identity alias template be a forwarding reference? It seems that the following code works in both Clang 3.7.0 (demo) and GCC 6.0.0 (demo): template <class T> using forwarding_reference = T&&; template <class T> void foo(forwarding_reference<T>) {} int main() { int...

Best way to deal with a trailing comma when using X macros in C++

c++,c++11,c++14,c-preprocessor
What's the best way to deal with extra trailing commas when working with X macros? Specifically, I have the following setup in a file test01.cpp struct Foo { #define X(name,val) int name; #include "test01.def" #undef X Foo() : #define X(name,val) name(val), #include "test01.def" #undef X {} }; int main(){ Foo...

Constructor and copy-constructor for class containing union with non-trivial members

c++,c++11,constructor,c++14,unions
I am trying to implement a custom variant type which uses a union to store data of various different types. In the field type_id I plan to store which type the data stored in the union is of. The union contains non-trivial members. Here is my current implementation: struct MyVariant...

Why did the C++ designers choose not to allow non-member operator()()?

c++,c++11,gcc,g++,c++14
I am just playing with std::function<> and operators, to make C++ statements look like Functional Languages(F#) and found out that there is a difference between operator() and operator<<. My code : Function 1 (Operator Overload): function<int(int)> operator>>(function<int(int)> f1, function<int(int)> f2) { function<int(int)> f3 = [=](int x){return f1(f2(x));}; return f3; }...

syntax for calling a method on a member with multiple instances

c++11,inheritance,c++14
I the following case template<typename T> class base{ public: void test(){} }; template<typename T> class helper{ public: base<T> t; }; template<typename T, typename ... Ts> class holder: public helper<T>, helper<Ts>... { }; int main(int argc, char *argv[]){ holder<int, short, long> h; h.t.test(); // of course, error here } Which compiles...

Is calling delete operator on a memory allocated by new[] operator undefined behavior?

c++,standards,c++14,delete-operator
I am pretty much sure it is but if I am interpreting correctly the standard (Section 18.6.1.2 new.delete.array) mentions that: void operator delete[](void* ptr) noexcept; pointer. . 13 Default behavior: Calls operator delete(ptr) Since in its default behavior delete[] just calls its delete(ptr) equivalent why should it matter which version...

Can an identity alias template be a forwarding reference?

c++,templates,alias,c++14,forwarding-reference
Consider the following snippet below: template <class T> using identity = T; template <class T> void foo(identity<T>&&) {} int main() { int i{}; foo(i); } i is an lvalue, hence if foo declares a forwarding reference parameter, it should compile. However, if identity<T>&& is turned to be int&&, it should...

Trying to understand [basic.def.odr]/2 in C++14 (N4140)

c++,language-lawyer,c++14
The Example in [basic.def.odr]/2 starts with the following sentence: In the following example, the set of potential results of the initializer of n contains the first S::x subexpression, but not the second S::x subexpression. From the definitions in this paragraph, how can we deduce that the initializer of n contains...

Different variadic template expansion

c++,c++11,variadic-templates,c++14
I want to prepare list of pairs of values from structure using variadic templates. #include <vector> struct foo { foo(int a, int b) : a(a), b(b) {} int a; int b; }; struct Msg { std::vector<int> valueArray; }; template<typename... Args> Msg func(Args... args) { Msg msg; msg.valueArray = { sizeof...(args),...

Create dummy object of non-default-constructible class

c++,c++14,default-constructor,sentinel
tl;dr: I want to construct a class ListEntry containing a member of a generic type Value, but Value is not default constructible and ListEntry doesn't know how to construct it. I will never access this Value member, so it doesn't matter that it isn't initialized. Why I'm doing this I'm...

deduce entire vector space at compile time

c++,templates,c++11,variadic-templates,c++14
Inspired by this question : c++ generate (xyz) points in range I began to wonder whether there is a form of template code that can, from this statement: using X = axis_limits<-10, +10>; using Y = axis_limits<-10, +10>; using Z = axis_limits<-10, +10>; auto space = std::vector<point>{ generate_point_space<X, Y, Z>...

HTTP Requests in C++ without external libraries? [closed]

c++,httprequest,c++14
So this question has been asked before, but the general answer pointed to was using an external library such as cURLpp. So I was curious as to if HTTP requests could be done using only the standard libraries as of C++14. How difficult would this be? Say for example, I...

Can `auto &&` parameters be perfect forwarded?

c++,c++14,perfect-forwarding
For template functions I use perfect forwarding like this: template<typename T> void f (T && v) { g (std::forward<T> (v)); } How do I perfect forward auto && parameters in C++14 lambda expressions? auto f = [] (auto && v) { g (std::forward<??> (v)); }; (Tried to google for it...

Initialise const fusion boost list from derived class

c++,boost,c++14,fusion
Is it possible to initialise a member fusion vector to a value specified in a derived class without making the base class a template class? like this: class container { const auto children; container (auto children):children (children){} } class derived : public container { derived():container(make_vector(string("test1"),string("test"))){} // http://www.boost.org/doc/libs/1_57_0/libs/fusion/doc/html/fusion/container/generation/functions/make_vector.html } I know...

Is there a way to iterate over at most N elements using range-based for loop?

c++,c++11,stl,c++14
I would like to know if there is a nice way to iterate over at most N elements in a container using the range based for loop and/or algorithms from the standard library (that's the whole point, I know I can just use the "old" for loop with a condition)....

Template specialization: ‘Scalar’ does not name a type

c++,templates,c++11,c++14,template-specialization
I'm trying to implement a template specialization for complex scalars and, with the help of Stackoverflow, got to using std::enable_if_t and its poor man's version #include <type_traits> #include <complex> // declarations namespace Test { template<class Scalar> class A { public: A(const Scalar z); Scalar realPart(); private: Scalar z_; }; }...

C++ Syntax: return statement with space after “template”; what does it mean [duplicate]

c++,boost,c++14,boost-interprocess
This question already has an answer here: Where and why do I have to put the “template” and “typename” keywords? 6 answers TL;DR: What does the following Syntax for the functions return type and the return statement mean? (Code from boost::interprocess) template <class T> typename segment_manager::template construct_proxy<T>::type construct(char_ptr_holder_t name)...

MPL replace without casting the fusion container

c++,boost,c++14,fusion,mpl
I have this class struct MyChildrenNeedsSpace : HaveChildren<MyChildrenNeedsSpace> { typedef childrenListType<string, string, string, string> context; const context children; MyChildrenNeedsSpace() : children("this", "sentence", "needs", "spaces") { std::cout << endl << "The children type is:" << endl << typeid(children).name() << endl; } }; it uses CRTP to allow the HaveChildren class to...

Linker error with variable templates

c++,templates,linker,c++14,template-variables
Consider the code below: #include <iostream> template<typename T> T n; int main() { n<int> = 42; std::cout << n<int> << std::endl; } It compiles and links with g++5.1, and it displays 42. However, clang++ fails to link it: undefined reference to n<int> If I initialize the template variable like template<typename...

Given cbegin(), cend(), why is there no cfront(), cback(), cfind(), …?

c++,stl,c++14
So, in order to allow code such as auto vect = ...; auto it = vect.begin(), end = vect.end(); // want const_iterator, getting iterator to pick the right overload of begin() and end(), even for non-const containers, the more explicit cbegin()/cend() functions were added. Why stop there? Associative containers have...

How is a lambda moved?

c++,c++11,lambda,c++14,move-semantics
I don't understand how a lambda is moved. Consider the following code: #include <iostream> #include <utility> #include <string> struct Foo // non-copyable type { Foo() = default; Foo(const Foo&) = delete; // cannot copy Foo(Foo&&) = default; // can move }; auto lambda = [p = Foo()](){ std::string x{"lambda"}; std::cout...

Is it possible to create a template alias?

c++,c++11,c++14,type-alias
Consider the following code: template< template< typename ... > class ... Ts > struct unite { template< typename ... T > struct type : Ts< T ... > ... { }; }; // This does not work as ::type does not name a type, but a template: // template< template<...

Is round-trip through floating point always defined behavior if floating point range is bigger?

c++,language-lawyer,c++14,floating-point-conversion
Let's say I have two arithmetic types, an integer one, I, and a floating point one, F. I also assume that std::numeric_limits<I>::max() is smaller than std::numeric_limits<F>::max(). Now, let's say I have a positive integer value i. Because the representable range of F is larger than I, F(i) should always be...

Disable Function when parameter type is void

templates,c++11,c++14,sfinae,enable-if
I have a template class looking like this: template <typename T> constexpr bool is_value_passable_v = is_trivially_copyable_v<T> && sizeof(T) <= sizeof(void*) && !is_polymorphic_v<T>; template <typename B, typename T> using param_base_t = conditional_t<is_value_passable_v<B>, T, const T&>; template <typename T> struct param_d { using type = param_base_t<T, T>; }; template <> struct param_d<void>...

Are new and delete still useful in C++14?

c++,c++11,new-operator,c++14,dynamic-memory-allocation
Given availability of make_unique and make_shared, as well as automatic deletion by unique_ptr and shared_ptr destructors, what are the situations (apart from supporting legacy code) for using new and delete in C++14?

C++ constexpr auto member function. Clang issue?

c++,c++11,auto,c++14,constexpr
#include <utility> struct A { constexpr auto one(int a) { return std::integral_constant<int, _data[a]>{}; } constexpr int two(int a) const { return _data[a]; } int _data[10]; }; int main() { constexpr auto ex = A{{1,2,3,4,5,6,7,8,9,10}}; std::integral_constant<int, ex.two(3)> b{}; } The code above will not compile in trunk Clang. The error...

Does OS X 10.7 libc++ support c++14?

c++,osx,osx-lion,c++14,libc++
I'm updating a project to use the latest Qt and taking the opportunity to switch to libc++ and C++11 at the same time. My understanding is that OS X 10.7 and above support this without me needing to ship my own build of the standard library. I'm happy to no...

clang 3.4 C++14 support

c++,c++14,clang++
I am using travis.ci to do automated test builds of my git repositories. For linux they use: Ubuntu 12.04 With clang 3.4 According to the clang page all C++ 14 language features are supported by Clang 3.4 (as long as you use the -std=c++1y flag). So far so good: I...

Pass template functor to a template std::function

c++,templates,c++11,c++14
Here is a code snippet: #include <functional> #include <iostream> #include <memory> template <typename T> using Callback = std::function<void(const T)>; template <typename T> void Call(const T yyy, const Callback<T>& callback) { callback(yyy); } template <typename T> class MyCallback { public: explicit MyCallback(const T counter_init) : counter_{counter_init} {} void operator ()(const T...

__cplusplus < 201402L return true in gcc even when I specified -std=c++14

c++,gcc,g++,c++14,predefined-macro
The directive: #ifndef __cplusplus #error C++ is required #elif __cplusplus < 201402L #error C++14 is required #endif The command-line: g++ -Wall -Wextra -std=c++14 -c -o header.o header.hpp My g++ version: g++ (tdm-1) 4.9.2 The error C++14 is required is generated even when I added -std=c++14, I don't know why. Please...

Floating point division by zero not constexpr

c++11,c++14,constexpr
When compiling this: constexpr double x {123.0}; constexpr double y = x / 0.0; std::cout << x << " / 0 = " << y << "\n"; The compiler (gcc 4.9.2, -std=c++11 or c++14) fails, giving error: (1.23e+2 / 0.0)' is not a constant expression constexpr double y = x...