SFINAE test: no output

I wanted to test some SFINAE but got stuck on the fact that the return statement on row 19 is not printing normal. I though I was doing something wrong but when I tested the same call one line abow it did print normal. Does that mean that it is being optimized away? I though optimizations that removed printing broke the as-if rule.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <type_traits>
#include <iostream>

using namespace std;

namespace details
{
    template <typename T, typename U>
    T add_pointers_helper(enable_if_t<(!is_pointer<U>::value), int> = {})
    {
        cout << "normal" << endl;
        return T{};
    }
    template <typename T, typename U>
    auto add_pointers_helper(enable_if_t<(is_pointer<U>::value), int> = {})
    {
        cout << "ptr" << endl;
        add_pointers_helper<int, int>(); //prints normal
        return add_pointers_helper<int,int>; //does not print normal
    }
}

int main()
{
    add_pointers_helper<int, int*>();
}
Do you mean:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <type_traits>
#include <iostream>

using namespace std;

namespace details {
	template <typename T, typename U>
	T add_pointers_helper(enable_if_t<(!is_pointer_v<U>), int> = {}) {
		cout << "normal\n";
		return T {};
	}

	template <typename T, typename U>
	auto add_pointers_helper(enable_if_t<(is_pointer_v<U>), int> = {}) {
		cout << "ptr\n";
		add_pointers_helper<int, int>();
		return add_pointers_helper<int, int>();
	}
}

int main() {
	details::add_pointers_helper<int, int*>();
}



ptr
normal
normal


Also consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <type_traits>
#include <iostream>

using namespace std;

namespace details {
	template <typename T, typename U>
	auto add_pointers_helper() {
		if constexpr (!is_pointer_v<U>) {
			cout << "normal\n";
			return T {};
		} else {
			cout << "ptr\n";
			add_pointers_helper<int, int>();
			return add_pointers_helper<int, int>();
		}
	}
}

int main() {
	details::add_pointers_helper<int, int*>();
}

Last edited on
Yep, just realized that. My bad.
Topic archived. No new replies allowed.