【发布时间】:2016-04-14 20:13:34
【问题描述】:
在尝试一些模板约束结构时,我在 Clang 3.7 中遇到了一个令人惊讶的行为:
struct constraint_success {};
struct constraint_failure {};
template<bool>
struct require_t {};
template<>
struct require_t<true> {
static constexpr constraint_success* result = nullptr;
};
template<>
struct require_t<false> {
static constexpr constraint_failure* result = nullptr;
};
template<bool Condition>
constexpr auto require = require_t<Condition>::result;
//A named dummy value, since we need a default
constexpr constraint_success* required = nullptr;
这个 decltype 在我的编译器中触发一个 SFINAE 上下文:
template<constraint_success* value>
using constraint = decltype(value);
相对于:
//template<constraint_success* value>
//using constraint = constraint_success*;
例子:
//define custom constraints
template<typename T>
constexpr auto Pointer = require<std::is_pointer<T>::value>;
template<typename T>
constexpr auto NotPointer = require<!std::is_pointer<T>::value>;
//constrain template parameters
template<typename T, constraint<Pointer<T>> = required>
void foo() {
std::cout << "Hello, pointer!\n";
}
template<typename T, constraint<NotPointer<T>> = required>
void foo() {
std::cout << "Hello, not pointer!\n";
}
int main() {
foo<int*>();
foo<int>();
return 0;
}
这是标准要求,还是“幸运”的编译器错误?
【问题讨论】:
标签: c++ language-lawyer c++14 template-meta-programming sfinae