【发布时间】:2020-09-28 17:38:05
【问题描述】:
我正在尝试使用 SFINAE 技术来检查 - 类/结构是否具有带有特定模板声明的 operator(),例如(稍微简化):
struct Simplified
{
// 1st operator - I need to detect its presence
template<typename T, int I>
void operator()(T& val1, double val2)
{
std::cout << std::to_string(val1 + val2) << std::to_string(I) << std::endl;
}
// 2nd operator
void operator()(double& val1, double val2)
{
std::cout << std::to_string(val1 + val2) << std::endl;
}
};
而且我一直在检查operator() 模板签名。这是我的助手类:
template<typename Fn, int I, typename T>
class TemplatedOperatorCheck
{
struct Exists { };
struct NotExists { };
template<typename U, void(U::*)(T&, double)> struct SFINAESimple {};
template<typename U> static Exists Test(SFINAESimple<U, &(U::operator())>*);
// The problem is probably there ^^^^^^^^^^^^^^^
template<typename U> static NotExists Test(...);
public:
static constexpr bool kExists = std::is_same<decltype(Test<Fn>(nullptr)), Exists>::value;
};
但是这个类只能检测到非模板operator()的存在。
// true if 2nd operator declared in Simplified class, false otherwise.
auto DoubleOpValid = TemplatedOperatorCheck<Simplified, 0, double>::kExists;
// always false
auto IntOpValid = TemplatedOperatorCheck<Simplified, 0, int>::kExists;
我做错了什么?在 Google 或 stackoverflow 中找不到任何相关内容...
提前致谢!任何帮助将不胜感激。
【问题讨论】:
-
std::is_invocable_v不会为你做这件事吗? -
我有点困惑...您希望测试仅检测第一个运算符,仅检测第二个运算符,还是同时检测两者?
-
@IgorG ,实际上我只需要检测第一个操作员的存在。第二个只是为了澄清不应检测到的内容。
标签: c++ templates template-meta-programming sfinae