【发布时间】:2020-08-04 12:50:20
【问题描述】:
我已阅读以下主题:
no type named ‘type’ in ‘struct std::enable_if<false, void>
Selecting a member function using different enable_if conditions
"What happened to my SFINAE" redux: conditional template class members?
但是,我似乎无法在 gcc 和 msvc 上解决这个相当简单的 SFINAE 问题:
#include <type_traits>
#include <iostream>
template<typename A, typename B>
class Test {
public:
template<typename X=A, typename = typename std::enable_if<std::is_same<X, void>::value, void>::type >
void foo() {
std::cout << "A";
}
template<typename X=A, typename = typename std::enable_if<!std::is_same<X, void>::value, void>::type >
void foo() {
std::cout << "B";
}
};
int main(int argc, char **argv) {
Test<int, float> t;
t.foo();
return 0;
}
实际结果:
A = void:完全错误:
main.cpp:15:8: error: 'template<class A, class B> template<class X, class> void Test<A, B>::foo()' cannot be overloaded with 'template<class A, class B> template<class X, class> void Test<A, B>::foo()'
15 | void foo() {
| ^~~
main.cpp:10:8: note: previous declaration 'template<class A, class B> template<class X, class> void Test<A, B>::foo()'
10 | void foo() {
| ^~~
A = int:完全错误:
main.cpp:15:8: error: 'template<class A, class B> template<class X, class> void Test<A, B>::foo()' cannot be overloaded with 'template<class A, class B> template<class X, class> void Test<A, B>::foo()'
15 | void foo() {
| ^~~
main.cpp:10:8: note: previous declaration 'template<class A, class B> template<class X, class> void Test<A, B>::foo()'
10 | void foo() {
| ^~~
main.cpp: In function 'int main(int, char**)':
main.cpp:26:9: error: no matching function for call to 'Test<int, float>::foo()'
26 | t.foo();
| ^
main.cpp:10:8: note: candidate: 'template<class X, class> void Test<A, B>::foo() [with X = X; <template-parameter-2-2> = <template-parameter-1-2>; A = int; B = float]'
10 | void foo() {
| ^~~
main.cpp:10:8: note: template argument deduction/substitution failed:
main.cpp:9:26: error: no type named 'type' in 'struct std::enable_if<false, void>'
9 | template<typename X=A, typename = typename std::enable_if<std::is_same<X, void>::value, void>::type >
| ^~~~~~~~
预期结果
A = void:输出“A”
A = int:输出“B”
我想要的是基于模板参数实现不同的(附加)成员函数。
但是,似乎我无法使 enable_if 依赖于类模板类型,但我不知道为什么。根据链接的线程,上面的代码显示是正确的。
你能解释一下为什么这不起作用吗?
【问题讨论】:
-
您跳过了编译器错误的重要部分。最好在问题中包含完整的错误
-
我已经添加了(我认为)初始错误,因为输出会非常糟糕。
-
但您在问题中包含的错误只是实际错误(您未包含)的结果
-
好的,添加了完整的编译输出。抱歉,我认为包含链接会更好
-
别担心,添加一个在线编译器的链接很好,但不是更好;)