Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Errors when using constexpr-if: expected '(' before 'constexpr'

I am trying to use if-constexpr to check something, but I encounter errors like

expected '(' before 'constexpr'

'else' without a previous 'if' "

So far i check there is nothing wrong with my codes

My compiling flag is g++ -std=c++17 main.cpp

#include <iostream>
template<typename T, typename Comp = std::less<T> >
struct Facility
{
template<T ... list>
struct List
{
    static void print()
    {
        std::cout<<"\""<<"Empty List"<<"\""<<"\n";
    }
};
template<T head,T ... list>
struct List<head,list...>
{
    static void print()
    {
        std::cout<<"\"" << head;
        ((std::cout << " " << list), ...);
        std::cout<<"\""<<"\n";
    }
};
template<unsigned N,typename AA>
struct RemoveFirst{};

template<unsigned N,T head,T ... Rest>
struct RemoveFirst<N,List<head,Rest...>>
{
    struct result
    {
        static void print()
        {   
            if constexpr (N == head)
            {
                std::cout<<"";
            }
            else
            {
                std::cout<<"\""<<head;
                ((std::cout << " " << Rest), ...);
                std::cout<<"\""<<"\n";
            }
        }
    };
 };
};
template<int ... intlist>
using IntList = typename Facility<int>::List<intlist...>;

int main()
{
 using IntFacility = Facility<int>;
 using List = IntList<2, 8, 2, 3, 5, 10, 8, 5>;
}
like image 526
Lim Ta Sheng Avatar asked Jul 11 '18 17:07

Lim Ta Sheng


People also ask

Can constexpr use if?

constexpr if can be used to replace several tricks that were already done: SFINAE technique to remove not matching function overrides from the overload set. you might want to look at places with C++14's std::enable_if - that should be easily replaced by constexpr if . Tag dispatch.

What is false constexpr?

In a constexpr if statement, the value of condition must be a contextually converted constant expression of type bool. If the value is true, then statement-false is discarded (if present), otherwise, statement-true is discarded.


1 Answers

Older versions of GCC (up to 6.x) which do not support the final version of C++17 will give that error, because they recognize constexpr as a keyword but do not understand the constexpr-if construct. Make sure your GCC is version 7 or later.

like image 163
Sneftel Avatar answered Oct 26 '22 07:10

Sneftel