【发布时间】:2018-12-03 13:02:32
【问题描述】:
我试图弄清楚为什么 SFINAE 不能使用直接模板参数初始化?
它以这种形式工作,当我在这里声明另一个模板参数时:
#include <iostream>
template <bool B, class T = void>
class enable_if {};
template <class T>
struct enable_if<true, T> { typedef T type; };
template <bool B, class T>
using enable_if_t = typename enable_if<B,T>::type;
template< typename T >
struct Y {
public:
template< typename U = T >
enable_if_t<true, U>
foo() {
return 111;
}
template< typename U = T >
enable_if_t<false, U>
foo() {
return 222;
}
};
int main() {
Y< double > y;
std::cout << y.foo() << std::endl;
}
(打印出 111)
但是如果我重构这个语法,编译器会报错:
#include <iostream>
template <bool B, class T = void>
class enable_if {};
template <class T>
struct enable_if<true, T> {
typedef T type;
};
template <bool B, class T>
using enable_if_t = typename enable_if<B,T>::type;
template< typename T >
struct Y {
template< typename U = enable_if_t<true, T> >
U
foo() {
return 11;
}
template< typename U = enable_if_t<false, T> >
U
foo() {
return 12;
}
};
int main() {
Y< double > y;
std::cout << y.foo() << std::endl;
}
“不能重新声明类成员”我假设第二个实例无效,应该被 SFINAE 排除?
为什么我不能像这样声明 foo():
enable_if_t<true, T> foo() { return 11; }
enable_if_t<false, T> foo() { return 12; }
仅基于类模板的 T 参数? 第二个 enable_if_t 应该无效,应该丢弃 foo() 的实例,对吧?
【问题讨论】:
标签: c++ templates template-meta-programming sfinae