我正在试着写一个SFINAE模板来决定两个类是否可以添加在一起。这主要是为了更好地理解SFINAE是如何工作的,而不是出于任何特定的“现实世界”原因。
所以我想出的是
#include <assert.h>
struct Vec
{
Vec operator+(Vec v );
};
template<typename T1, typename T2>
struct CanBeAdded
{
struct One { char _[1]; };
struct Two { char _[2]; };
template<typename W>
static W make();
template<int i>
struct force_int { typedef void* T; };
static One test_sfinae( typename force_int< sizeof( make<T1>() + make<T2>() ) >::T );
static Two test_sfinae( ... );
enum { value = sizeof( test_sfinae( NULL ) )==1 };
};
int main()
{
assert((CanBeAdded<int, int>::value));
assert((CanBeAdded<int, char*>::value));
assert((CanBeAdded<char*, int>::value));
assert((CanBeAdded<Vec, Vec>::value));
assert((CanBeAdded<char*, int*>::value));
}这将编译除最后一行之外的所有代码,它给出了
finae_test.cpp: In instantiation of ‘CanBeAdded<char*, int*>’:
sfinae_test.cpp:76: instantiated from here
sfinae_test.cpp:40: error: invalid operands of types ‘char*’ and ‘int*’ to binary ‘operator+’所以这个错误是我所期望的,但是我希望编译器能够找到test_sfinae( ... )定义并使用它(而不是抱怨不能解析的那个。
显然我漏掉了什么,我只是不知道它是什么。
发布于 2010-01-15 15:02:07
在我看来,您遇到了在Core Issue 339和N2634中讨论的问题。底线是,即使你正在做的事情是标准允许的,你也会超出任何编译器目前所能处理的范围。C++ 0x将添加更多关于什么将导致和不会导致SFINAE失败与硬错误的详细信息。如果你想深入了解血淋淋的细节,请参阅N3000,§14.9.2。
https://stackoverflow.com/questions/2069744
复制相似问题