SFINAE : Delete a function with the same prototype

白昼怎懂夜的黑 提交于 2020-05-07 19:00:25

问题


I wonder what is the difference between this code that works :

#include <type_traits>
#include <iostream>

template<typename T> using is_ref = std::enable_if_t<std::is_reference_v<T>, bool>;
template<typename T> using is_not_ref = std::enable_if_t<!std::is_reference_v<T>, bool>;

template<typename T, is_ref<T> = true>
void foo(T&&) {
    std::cout << "ref" << std::endl;
}

template<typename T, is_not_ref<T> = true>
void foo(T&&) {
    std::cout << "not ref" << std::endl;
}

int main() {
    int a = 0;
    foo(a);
    foo(5);
}

and this one that does not work :

#include <type_traits>
#include <iostream>

template<typename T> using is_ref = std::enable_if_t<std::is_reference_v<T>, bool>;
template<typename T> using is_not_ref = std::enable_if_t<!std::is_reference_v<T>, bool>;

template<typename T, typename = is_ref<T>>
void foo(T&&) {
    std::cout << "ref" << std::endl;
}

template<typename T, typename = is_not_ref<T>>
void foo(T&&) {
    std::cout << "not ref" << std::endl;
}

int main() {
    int a = 0;
    foo(a);
    foo(5);
}

What is the true difference between typename = is_ref<T> and is_ref<T> = true ?


回答1:


If you remove the default template arguments, it'll become clear what the difference is. Function declarations cannot differ in just their defaults. This is ill-formed:

void foo(int i = 4);
void foo(int i = 5);

And likewise this is ill-formed:

template <typename T=int> void foo();
template <typename T=double> void foo();

With that in mind, your first case:

template<typename T, is_ref<T>>
void foo(T&&);

template<typename T, is_not_ref<T>>
void foo(T&&);

The two declarations here are unique because the second template parameter differs between the two declarations. The first has a non-type template parameter whose type is std::enable_if_t<std::is_reference_v<T>, bool> and the second has a non-type template parameter whose type is std::enable_if_t<!std::is_reference_v<T>, bool>. Those are different types.

Whereas, your second case:

template<typename T, typename>
void foo(T&&);

template<typename T, typename>
void foo(T&&)

This is clearly the same signature - but we've just duplicated it. This is ill-formed.


See also cppreference's explanation.



来源:https://stackoverflow.com/questions/50440352/sfinae-delete-a-function-with-the-same-prototype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!