以下代码正确地确定了何时可以为给定的Writer( t )
调用T
。
template <typename T>
inline void Process( const T& t )
{
if constexpr ( std::is_invocable<decltype(Writer), const T&>::value )
{
Writer( t );
}
else { //... }
}
但是我只能让它适用于Writer中定义的
operator()
,例如class Writer
{
public:
operator()( const int& )
{
\\...
}
}
如何为成员函数获得相同的检查,即检查该函数是否存在,例如用于
Write(...)
class Writer
{
public:
inline void Write( const int& t )
{
}
};
class Archive
{
public:
template <typename T>
inline void Process( const T& t )
{
//check if Writer can handle T
if constexpr ( std::is_invocable_v<decltype( ???&Writer::Write??? ), ???, const T&> )
{
TheWriter.Write( t );
std::cout << "found";
}
else
{
std::cout << "not found";
}
}
Writer TheWriter;
};
我在
Writer.Write
中尝试过的Writer::Write
,decltype
,&
和if constexpr
的每种可能组合都会导致编译器错误,甚至fatal error C1001
。这在带有/ std:c++ 17的Visual Studio 2017 MSVC_1916上。
最佳答案
您可以像这样检查成员函数:
template <typename T>
inline void Process( const T& t )
{
if constexpr ( std::is_invocable_v<decltype(&Writer::Write), Writer&, T const &> )
{
Writer{}.Write(t);
}
else
{
//...
}
}
这是一个有效的demo。感谢@aschepler指出原始代码段中的错误。
关于c++ - std::is_invocable <…>检查成员函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61260441/