Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is enable_if only C++11?

Tags:

c++

Looking on the C++ reference website for enable_if, it is said to be only a C++11 feature.

However, I compiled my own version of enable_if using the GCC compiler on the C++98 type, which worked perfectly and seemed to be able to work for any version of C++ (1 is printed):

#include <iostream>

namespace egg
    {
    template<bool B,
        typename T = void>
        struct enable_if
        {
        };

    template<typename T>
        struct enable_if<true, T>
        {
        typedef T type;
        };
    }

int main()
    {
    egg::enable_if<1 == 1, int>::type x = 1;
    std::cout << x << std::endl;
    }

Am I right in saying the enable_if is effectively a feature for any C++ version but was only introduced into the C++ standard or is there another reason for this?

like image 367
user3476093 Avatar asked Jul 26 '15 14:07

user3476093


People also ask

What is Enable_if in C++?

The enable_if family of templates is a set of tools to allow a function template or a class template specialization to include or exclude itself from a set of matching functions or specializations based on properties of its template arguments.

When to use enable_ if?

std::enable_if can be used in many forms, including: as an additional function argument (not applicable to operator overloads) as a return type (not applicable to constructors and destructors) as a class template or function template parameter.


1 Answers

enable_if was added to the standard in C++11(source). It does not rely on any C++11 standard features and so it code be coded by yourself in C++03 as you can see from this possible implementation

template<bool B, class T = void>
struct enable_if {};

template<class T>
struct enable_if<true, T> { typedef T type; };

This is just using template metaprograming and SFINAE.

You could also use boost::enable_if instead of writing your own which is also C++98/03 compatible.

like image 97
NathanOliver Avatar answered Oct 31 '22 15:10

NathanOliver