67

Consider following code:

#include <iostream>
#include <type_traits>

template <typename T>
struct A {
    int val = 0;

    template <class = typename std::enable_if<T::value>::type>
    A(int n) : val(n) {};
    A(...) { }

    /* ... */
};

struct YES { constexpr static bool value = true; };
struct NO { constexpr static bool value = false; };

int main() {
    A<YES> y(10);
    A<NO> n;
    std::cout << "YES: " << y.val << std::endl
              << "NO:  " << n.val << std::endl;
}

I want to selectively define constructor A::A(int) only for some types using enable_if. For all other types there is default constructor A::A(...) which should be the default case for compiler when substitution fails. However this makes sense for me compiler (gcc version 4.9.0 20130714) is still complaining

sfinae.cpp: In instantiation of 'struct A': sfinae.cpp:19:11:
required from here sfinae.cpp:9:5: error: no type named 'type' in
'struct std::enable_if'
A(int n) : val(n) {};

Is something like this possible for constructor? Is this possible with another constructor(s) (copy-constructor and move-constructor)?

tomas789
  • 1,280
  • 1
  • 9
  • 21

3 Answers3

57

I think this can't work with a single defaulted template parameter, because its value needs to be resolved when the class template is instantiated.

We need to defer the substitution to the point of constructor template instantiation. One way is to default the template parameter to T and add an extra dummy parameter to the constructor:

template<typename U = T>
A(int n, typename std::enable_if<U::value>::type* = 0) : val(n) { }
jrok
  • 54,456
  • 9
  • 109
  • 141
  • better explanation than mine :D – Joel Falcou Jul 24 '13 at 19:04
  • @JoelFalcou Yours actually works. [This one doesn't still](http://coliru.stacked-crooked.com/view?id=15f3b29d734e0b4f765cf6fddc19896d-fcf98f666e0b68774061981371328429) – Rapptz Jul 24 '13 at 19:10
  • @Rapptz My bad that's because it's used in a default template parameter. It needs to be in constructor's signature. I'll fix it. – jrok Jul 24 '13 at 19:25
  • Yes, this is very elegant. I'm afraid that this does not work. Could you give us explanation why even if it should as you described in your's answer? – tomas789 Jul 24 '13 at 19:28
  • @jrok Even if it is on the constructor's signature (as noted in a previous answer) it will not work. – Rapptz Jul 24 '13 at 19:34
  • @Rapptz Yes, I was completely off, thanks for heads up. It's fixed now. – jrok Jul 24 '13 at 19:45
  • 4
    @jrok It's [more common to put it in the template parameters](http://coliru.stacked-crooked.com/view?id=a885f2da5f9f372004981a056f99d8f4-fcf98f666e0b68774061981371328429), but yes you're right that this isn't possible with a single template parameter (that's actually the answer to the question). – Rapptz Jul 24 '13 at 19:48
  • I'm curious about the overhead of passing in the dummy parameter. Would most compilers be smart enough to optimise that out if this was in a header file? – bb94 Mar 24 '18 at 11:21
  • 3
    @bb94 So was I, so I tested on gcc 9.3.0 (mingw). Without -O it does not optimize it out. With -O1 it drops it, and also inlines the entire constructor. (Based on examining decompiled bin). – memtha Apr 03 '20 at 17:12
  • 1
    this is genious, thanks! i use the following hybrid without an extra parameter: template ::type> – Kikaxa May 13 '22 at 21:56
23

With C++20

You can achieve that simply by adding requires to the template:

template <typename U = T> requires U::value
A(int n) : val(n) { }

The requires clause gets a constant expression that evaluates to true or false deciding thus whether to consider this method in the overload resolution, if the requires clause is true, or ignore it otherwise.

Code: https://godbolt.org/z/CKTDFE

Amir Kirsh
  • 12,564
  • 41
  • 74
  • 3
    I'm choosing this as an answer as it seems to be the most compliant one with the newest C++ standard. For people who need to be backward-compatible I'd still recommend @jrok's answer as it works just fine. – tomas789 Nov 06 '20 at 23:07
14

Usually this is done using an anonymous defaulted argument :

A(int n, typename std::enable_if<T::value>::type* = 0) : val(n) {};

You can not use template parameters from the class to SFINAE out methods. SO one way is to add a dummy type replacing int :

see: http://ideone.com/2Gnyzj

#include <iostream>
#include <type_traits>

template <typename T>
struct A {
    int val = 0;

    template<typename Integer
            ,typename  = typename std::enable_if<T::value && sizeof(Integer)>::type
            >
    A(Integer n) : val(n) {};

    A(...) {}
    /* ... */
};

struct YES { constexpr static bool value = true; };
struct NO { constexpr static bool value = false; };

int main() {
    A<YES> y(10);
    A<NO> n;
    std::cout << "YES: " << y.val << std::endl
              << "NO:  " << n.val << std::endl;
}

This works because you use a member template parameter to SFINAE out the constructor but the test is always true so it doesn't pollute your checks

Joel Falcou
  • 6,247
  • 1
  • 17
  • 34