【发布时间】:2017-12-23 16:14:01
【问题描述】:
我正在尝试递归应用 type_trait has_fun 以便 C 仅在 T 具有成员函数时启用其 fun 成员函数。
有没有办法让C::fun 被有条件地检测到?
template <typename T>
struct has_fun {
template <class, class> class checker;
template <typename U>
static std::true_type test(checker<U, decltype(&U::fun)> *);
template <typename U>
static std::false_type test(...);
static const bool value = std::is_same<std::true_type, decltype(test<T>(nullptr))>::value;
};
struct A {
void fun(){
std::cout << "this is fun!" << std::endl;
}
};
struct B {
void not_fun(){
std::cout << "this is NOT fun!" << std::endl;
}
};
template<typename T>
struct C {
void fun() {
static_assert(has_fun<T>::value, "Not fun!");
t.fun();
}
T t;
};
int main(int argc, char const *argv[])
{
std::cout << has_fun<A>::value << std::endl;
std::cout << has_fun<B>::value << std::endl;
std::cout << has_fun<C<A>>::value << std::endl;
std::cout << has_fun<C<B>>::value << std::endl;
}
输出:
1
0
1
1
预期输出:
1
0
1
0
【问题讨论】:
标签: c++ c++11 templates sfinae enable-if