【发布时间】:2012-08-05 04:22:17
【问题描述】:
我见过这个question,它允许人们检查是否存在成员函数,但我试图找出一个类是否具有成员类型强>。
在下面的示例中,两者都评估为“false”,但我想找到一种方法,使 has_bar<foo1>::value 评估为 false,has_bar<foo2>::value 评估为 true。
这可能吗?
#include <iostream>
struct foo1;
struct foo2 { typedef int bar; };
template <typename T>
class has_bar
{
typedef char yes;
typedef long no;
template <typename C> static yes check( decltype(&C::bar) ) ;
template <typename C> static no check(...);
public:
enum { value = sizeof(check<T>(0)) == sizeof(yes) };
};
int main()
{
std::cout << has_bar<foo1>::value << std::endl;
std::cout << has_bar<foo2>::value << std::endl;
return 0;
}
编辑:针对以下答案实施专业化:
...如果您在目标模板中使用 C::bar,则模板将为 对于没有该嵌套类型的类型自动丢弃。
我尝试过这样做,但显然缺少一些东西
#include <iostream>
struct foo1;
struct foo2 { typedef int bar; };
template <typename T, typename U = void>
struct target
{
target()
{
std::cout << "default target" << std::endl;
}
};
template<typename T>
struct target<T, typename T::bar>
{
target()
{
std::cout << "specialized target" << std::endl;
}
};
int main()
{
target<foo1>();
target<foo2>();
return 0;
}
【问题讨论】:
-
foo1不完整——这是故意的吗?
标签: c++ c++11 template-meta-programming sfinae