如果类具有像这样的特殊成员函数(在另一个示例中可在此处找到),我会尝试专门化模板:
template <typename T>
class has_begin
{
typedef char one;
typedef long two;
template <typename C> static one test( decltype( &C::AnyFunc) ) ;
template <typename C> static two test(...);
public:
enum { value = sizeof(test<T>(0)) == sizeof(char) };
enum { Yes = sizeof(has_begin<T>::test<T>(0)) == 1 };
enum { No = !Yes };
};
这在 AnyFunc
被重载之前一直有效:
class B : public vector<int>
{
public:
void AnyFunc() const;
void AnyFunc();
};
如何重写我的测试代码以从我的模板中获得"is"?
最佳答案
使用不带参数的重载函数名 (13.4p1) 必须解析为单个重载 (13.4p4),否则将发生替换失败。
如果您正在测试成员函数的存在,那么您应该知道您计划调用它的参数:
template <typename C> static one test(
typename std::add_pointer<decltype(std::declval<C>().AnyFunc())>::type);
通常,您可以使用可变参数模板和类似于result_of
的模式:
template <typename C, typename... Args> static one test(
typename std::add_pointer<decltype(
std::declval<C>(std::declval<Args>()...).AnyFunc())>::type);
使用 add_pointer
允许它使用不允许作为函数参数类型的函数返回类型(例如 void
)。
关于c++ - 检查重载成员函数是否存在的模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13341676/