3
我試圖應用於http://www.drdobbs.com/tools/227500449概念檢查編譯錯誤上的gcc
隨着下面的代碼示例中描述的技術,我期望的輸出:
而且這確實是發生了什麼如果我用clang編譯的話。但是用gcc,這個代碼給出了以下錯誤:
junk.cpp: In instantiation of ‘const bool has_foo_member_variable<B>::value’:
junk.cpp:45:5: instantiated from ‘void print() [with T = B]’
junk.cpp:82:14: instantiated from here
junk.cpp:30:75: error: ‘B::foo’ is not a valid template argument for type ‘int B::*’
junk.cpp:30:75: error: it must be a pointer-to-member of the form `&X::Y'
junk.cpp: In instantiation of ‘const bool has_foo_member_variable<D>::value’:
junk.cpp:45:5: instantiated from ‘void print() [with T = D]’
junk.cpp:84:14: instantiated from here
junk.cpp:30:75: error: ‘& D::foo’ is not a valid template argument for type ‘int D::*’
junk.cpp:30:75: error: it must be a pointer-to-member of the form `&X::Y'
我用gcc 4.5.1 ......我看起來像的gcc沒有按照正確的SFINAE規則,但我不是100%肯定。鏗鏘聲是否正確,這是一個gcc錯誤?
#include <iostream>
struct small_type { char dummy; };
struct large_type { char dummy[2]; };
template<class T>
struct has_foo_member_function
{
template<int (T::*)()> struct tester;
template<class U> static small_type has_foo(tester<&U::foo> *);
template<class U> static large_type has_foo(...);
static const bool value = (sizeof(has_foo<T>(0)) == sizeof(small_type));
};
template<class T>
struct has_foo_static_member_function
{
template<int (*)()> struct tester;
template<class U> static small_type has_foo(tester<&U::foo> *);
template<class U> static large_type has_foo(...);
static const bool value = (sizeof(has_foo<T>(0)) == sizeof(small_type));
};
template<class T>
struct has_foo_member_variable
{
template<int T::*> struct tester;
template<class U> static small_type has_foo(tester<&U::foo> *);
template<class U> static large_type has_foo(...);
static const bool value = (sizeof(has_foo<T>(0)) == sizeof(small_type));
};
template<class T>
struct has_foo_static_member_variable
{
template<int *> struct tester;
template<class U> static small_type has_foo(tester<&U::foo> *);
template<class U> static large_type has_foo(...);
static const bool value = (sizeof(has_foo<T>(0)) == sizeof(small_type));
};
template<class T>
void print()
{
std::cout << has_foo_member_function<T>::value << " "
<< has_foo_static_member_function<T>::value << " "
<< has_foo_member_variable<T>::value << " "
<< has_foo_static_member_variable<T>::value << "\n";
}
struct A
{
int foo()
{
return 0;
}
};
struct B
{
static int foo()
{
return 0;
}
};
struct C
{
int foo;
};
struct D
{
static int foo;
};
int main()
{
print<A>();
print<B>();
print<C>();
print<D>();
}
我無法確認這是否是正確的C++或不。但是如果大多數情況下都支持,我可以再次確認一個有利於編譯器的編譯器。 Visual C++對它沒有任何問題,並且輸出與您所描述的完全相同。 – 2010-10-24 04:51:03