我编写了这段代码来检查类类型是否具有begin函数.
struct foo //a simple type to check
{
int begin(){ return 0;}
};
struct Fallback
{
int begin(){ return 0;}
};
template<typename T>
struct HasfuncBegin : T,Fallback
{
typedef char one;
typedef int two;
template<typename X>
static one check(int (X::*)() = &HasfuncBegin<T>::begin);
template<typename X>
static two check(...);
enum :bool {yes = sizeof(check<T>())==1, no= !yes};
};
int main()
{
std::cout<< HasfuncBegin<foo>::yes;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
哪会产生错误:
error: call of overloaded 'check()' is ambiguous
enum {yes = sizeof(check<T>())==1, no= !yes};
^
C:\XXX\main.cpp:24:16: note: candidate: static HasfuncBegin<T>::one HasfuncBegin<T>::check(int (X::*)()) [with X = foo; T = foo; HasfuncBegin<T>::one = char]
static one check(int (X::*)() = &HasfuncBegin<T>::begin);
^
C:\XXX\main.cpp:26:16: note: candidate: static HasfuncBegin<T>::two HasfuncBegin<T>::check(...) [with X = foo; T = foo; HasfuncBegin<T>::two = int]
static two check(...);
^
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释为什么调用是模糊的(即使首先检查函数与签名one check(int (X::*)() = &HasfuncBegin<T>::begin);使用默认参数)以及如何使我的代码工作?
编辑:
所以这是最终的工作代码:
struct foo
{
int begin(){ return 0;}
};
struct Fallback
{
int begin(){ return 0;}
};
template<typename T, T ptr> struct dummy{};
template<typename T>
struct HasfuncBegin : T,Fallback
{
typedef char one;
typedef int two;
template<typename X>
static one check(dummy<int (X::*)(),&HasfuncBegin<X>::begin>*);
// even this won't work, so replace above statement with below commented one
// static one check(dummy<decltype(&HasfuncBegin<X>::begin),&HasfuncBegin<X>::begin>*);
template<typename X>
static two check(...);
enum {yes = sizeof(check<T>(0))==1, no= !yes};
};
Run Code Online (Sandbox Code Playgroud)
该调用是不明确的,因为重载选择是基于从调用参数到函数参数的转换序列。在这里完整解释这些规则有点复杂,但请考虑以下两个示例:
void ex1(int) {} //v1
void ex1(...) {} //v2
void ex2(int = 1) {} //v1
void ex2(...) {} //v2
int main() {
ex1(1);
ex2();
}
Run Code Online (Sandbox Code Playgroud)
该ex1(1)调用格式良好。有一个参数具有比v1(v2精确匹配与省略号转换)更好的隐式转换序列。
该ex2()调用格式不正确。没有用于比较转换序列的参数,并且两个重载都可以在不带参数的情况下调用。这类似于您的代码。
看来您被 C++03 困住了,所以这里有一个使用这个答案的可能解决方案:
template<typename T>
struct HasfuncBegin {
typedef char yes[1];
typedef char no [2];
template <typename U, U> struct type_check;
template <typename _1> static yes &chk(type_check<int (T::*)(), &_1::begin > *);
template <typename > static no &chk(...);
static bool const value = sizeof(chk<T>(0)) == sizeof(yes);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
496 次 |
| 最近记录: |