Why can't I reload the template?

Why is this compiling:

class Testable {
public:
    template <bool flag>
    typename std::enable_if<flag>::type
    void foo() { cout << "Yay" << endl; }

    template <bool flag>
    typename std::enable_if<!flag>::type
    void foo() { cout << "Nay" << endl; }
};

But not if I define both foos using the default types, for example:

    template <bool flag, typename = typename std::enable_if<flag>::type>
    void foo() { cout << "Yay" << endl; } // (A)

    template <bool flag, typename = typename std::enable_if<!flag>::type>
    void foo() { cout << "Nay" << endl; } // (B)

I get this error (the first line points to the definition (B), the second points to (A)):

error: 'template<bool flag, class> void Testable::foo()' cannot be overloaded
error: with 'template<bool flag, class>> void Testable::foo()'
+5
source share
2 answers

The compiler complains because the two function templates have the same signature . Paragraph 1.3.18 of the C ++ 11 standard indicates that the signature of a function template is defined as follows:

<function template> name, parameter type list (8.3.5), covering the namespace (if any), return type, and template parameter list

As you can see, the default template arguments are not part of the signature.

, Testable :

class Testable {
public:
    template <bool flag, typename std::enable_if<flag>::type* = nullptr>
    void foo() { cout << "Yay" << endl; } // (A)

    template <bool flag, typename std::enable_if<!flag>::type* = nullptr>
    void foo() { cout << "Nay" << endl; } // (B)
};
+5

, .

.

template<std::size_t>
struct secret_enum { enum class type {}; };
template<bool b, std::size_t n=0>
using EnableIf = typename std::enable_if< b, typename secret_enum<n>::type >::type;

class Testable {
public:
  template <bool flag, EnableIf<flag, 0>...>
  void foo() { cout << "Yay" << endl; } // (A)

  template <bool flag, EnableIf<!flag, 1>...>
  void foo() { cout << "Nay" << endl; } // (B)
};

0, 1 .., , ... "0 ", enum .

, clang 3.2. gcc 4.8.

0

All Articles