[英]template to check for existence of overloaded member function
I try to specialize a template if a class has a special member function like this (found here in another example): 如果一个类有一个像这样的特殊成员函数(在另一个例子中找到),我尝试专门化一个模板:
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 };
};
This works well until AnyFunc
is overloaded: 这很有效,直到
AnyFunc
重载:
class B : public vector<int>
{
public:
void AnyFunc() const;
void AnyFunc();
};
How can I rewrite my test code to get a "Yes" from my template? 如何从我的模板中重写我的测试代码以获得“是”?
The use of an overloaded function name without arguments (13.4p1) must be resolved to a single overload (13.4p4), otherwise substitution failure will occur. 必须将使用不带参数的重载函数名称(13.4p1)解析为单个重载(13.4p4),否则将发生替换失败。
If you are testing for the existence of a member function then you should know the arguments you plan to call it with: 如果您正在测试是否存在成员函数,那么您应该知道您计划使用的参数:
template <typename C> static one test(
typename std::add_pointer<decltype(std::declval<C>().AnyFunc())>::type);
In general, you can use a variadic template and a pattern similar to result_of
: 通常,您可以使用可变参数模板和类似于
result_of
的模式:
template <typename C, typename... Args> static one test(
typename std::add_pointer<decltype(
std::declval<C>(std::declval<Args>()...).AnyFunc())>::type);
Using add_pointer
allows this to work with function return types that are not allowable as function argument types (eg void
). 使用
add_pointer
允许它使用add_pointer
作为函数参数类型的函数返回类型(例如void
)。
Found the version which works: 找到有效的版本:
template <typename C> static one test( decltype(((C*)0)->AnyFunc())* ) ;
If you want to verify that object has const function, use this: 如果要验证该对象是否具有const函数,请使用:
template <typename C> static one test( decltype(((const C*)0)->AnyFunc())* ) ;
this version will not detect function with arguments: 此版本不会检测带参数的函数:
class B : public std::vector<int>
{
public:
//void AnyFunc() const;
//void AnyFunc();
int AnyFunc(int);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.