【发布时间】:2020-03-19 13:31:00
【问题描述】:
以下问题: 我想检查模板化方法是否存在,因此我调整了此处给出的示例: Is it possible to write a template to check for a function's existence?
#include <cstdio>
#include <type_traits>
#define CHECK4_MEMBER_FUNC(RETTYPE,FUNCTION,...) \
template <class ClassType> \
class CIfCheck_##FUNCTION \
{\
private: \
template <class MemberPointerType> \
static std::true_type testSignature(RETTYPE (MemberPointerType::*)(__VA_ARGS__)); \
\
template <class MemberPointerType> \
static std::false_type testExistence(...); \
\
template <class MemberPointerType> \
static decltype(testSignature(&MemberPointerType::FUNCTION)) testExistence(std::nullptr_t); \
public: \
using type = decltype(testExistence<ClassType>(nullptr));\
static const bool value = type::value; \
};
class Bla
{
public:
template <typename SomeType>
bool init(SomeType someValue)
{
///
return true;
}
void exec()
{
return;
}
};
CHECK4_MEMBER_FUNC(bool, init, int);
CHECK4_MEMBER_FUNC(void, exec, void);
int main()
{
Bla blaObj;
blaObj.init<int>(2);
static_assert(CIfCheck_exec<Bla>::value, "no exec");
static_assert(CIfCheck_init<Bla>::value, "no init");
return 0;
}
但不幸的是,init() 触发了 static_assert()(因为在 main() 中实例化对象时,可能会在稍后评估特化)。
我尝试了显式成员专业化,但仍然失败:
template<>
bool Bla::init<int>(int item)
{
int temp = item*2; // do with item something
return false;
}
P.S.:附带问题(可能另一个问题主题更有意义:
std::false_type testExistence(...);
为什么我必须在这里传递一个参数?如果我删除可变参数... 选项(以及nullptr 和nullptr_t),由于testExistence() 的不明确存在而导致编译器错误。
【问题讨论】:
标签: c++ c++11 templates sfinae