#include <iostream>
#include <string>
template<class T>
auto optionalToString(T* obj)
-> decltype( obj->toString() )
{
return obj->toString();
}
auto optionalToString(...) -> std::string
{
return "toString not defined";
}
struct TA
{
std::string toString() const
{
return "Hello";
}
};
struct TB
{
};
Question>给出了提议的解决方案optionalToString
,我如何使用它来检测TA有toString,而TB没有。
发布于 2017-04-18 14:44:51
一种基于can_apply
的this code解决方案
template<class T>
using toString_result = decltype(std::declval<T>().toString());
template<class T>
constexpr auto has_toString = can_apply<toString_result, T>::value;
像这样使用:
struct TA
{
std::string toString() const
{
return "Hello";
}
};
struct TB
{
};
int main()
{
std::cout << has_toString<TA> << '\n';
std::cout << has_toString<TB> << '\n';
return 0;
}
DEMO
发布于 2017-04-18 16:19:50
给定的解决方案允许您始终从任何对象获取字符串。如果它有一个toString()
成员函数,这将被使用,否则,一个默认字符串。鉴于上述情况,使用示例:
TA a;
TB b;
std::cout << "a: " << optionalToString(&a) << '\n';
std::cout << "b: " << optionalToString(&b) << std::endl;
但是,无论a
还是b
是否有toString()
方法,您都不会得到布尔值。如果你想要的话,你需要像O‘’Neil提出的解决方案。
https://stackoverflow.com/questions/43474174
复制相似问题