我正在玩SFINAE,但我正在尝试在处理宏生成的代码时获得一些有意义的编译器错误信息。我使用THIS answer来运行以下命令: (我想用member_test检查(a)类型A是否有一些先前定义的成员)
//Check for member variable with given name.
#define CREATE_MEMBER_VAR_CHECK(var_name) \
\
template<typename T, typename = std::true_type> \
struct has_member_var_##var_name : std::false_type {}; \
\
template<typename T> \
struct has_member_var_##var_name< \
T \
, std::integral_constant< \
bool, std::is_member_object_pointer<decltype(&T::var_name)>::value \
> \
> : std::true_type {};
#define MEMB_CHECK_WRAPPER(r, data, elem) CREATE_MEMBER_VAR_CHECK(elem)
#define CREATE_ENABLE_IF_CLAUSE(var_name) \
class = typename std::enable_if<has_member_var_##var_name<T>::value>::type
#define ENABLE_IF_CLAUSE_WRAPPER(r, data, i, elem) \
BOOST_PP_COMMA_IF(i) CREATE_ENABLE_IF_CLAUSE(elem)
#define TO_MEMBER_TEST(member_seq) \
BOOST_PP_SEQ_FOR_EACH(MEMB_CHECK_WRAPPER, _, member_seq) \
\
template < typename T, \
BOOST_PP_SEQ_FOR_EACH_I(ENABLE_IF_CLAUSE_WRAPPER, _, member_seq) \
> \
void member_test(const T & ) \
{ \
std::cout << "works!!\n\n"; \
}
当我接着做以下事情时,一切都会好起来的:
TO_MEMBER_TEST((x)(y)(z))
struct A { int x, y, z; };
int main(int argc, char const *argv[])
{
A a;
member_test(a);
}
但是,当我使用TO_MEMBER_TEST((x)(y)(z)(dummy))
代替时,代码将无法编译(按预期),因为不再定义member_test(A&amp;),因为A.dummy不存在。编译器会给我一些类似的东西:
模板参数推导/替换失败:错误:'struct std :: enable_if'中没有名为'type'的类型
我怎么能说'没有成员假人'之类的话。相反(例如使用static_asserts)?
答案 0 :(得分:0)
嗯,实际上当我真的想要使用static_assert的特定编译器错误时,enable_if是不必要的,所以我提出了这个解决方案:
//Check for member variable with given name.
#define CREATE_MEMBER_VAR_CHECK(var_name) \
\
template<typename T, typename = std::true_type> \
struct has_member_var_##var_name : std::false_type {}; \
\
template<typename T> \
struct has_member_var_##var_name< \
T \
, std::integral_constant< \
bool, std::is_member_object_pointer<decltype(&T::var_name)>::value \
> \
> : std::true_type {};
#define MEMB_CHECK_WRAPPER(r, data, elem) CREATE_MEMBER_VAR_CHECK(elem)
#define MEMBER_ERROR(type_name, var_name) \
#var_name is not a member of #type_name
#define CHECK_HAS_MEMBER(type_name, var_name) \
static_assert(has_member_var_##var_name<type_name>::value, \
BOOST_PP_STRINGIZE(MEMBER_ERROR(type_name, var_name)) );
#define CHECK_HAS_MEMBER_WRAPPER(r, data, elem) CHECK_HAS_MEMBER(data, elem)
#define TO_MEMBER_TEST(type, member_seq) \
BOOST_PP_SEQ_FOR_EACH(MEMB_CHECK_WRAPPER, _, member_seq) \
BOOST_PP_SEQ_FOR_EACH(CHECK_HAS_MEMBER_WRAPPER, type, member_seq) \
\
template < typename type> \
void member_test(const type & ) \
{ \
std::cout << "works!!\n\n"; \
}
struct A { int x, y, z; };
TO_MEMBER_TEST(A,(x)(y)(z)(dummy))
将调用CHECK_HAS_MEMBER()
添加到宏CREATE_MEMBER_VAR_CHECK
的末尾会使其更具“可读性”。