4

我正在尝试编写一个 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( ... ) 定义并使用它(而不是抱怨不解析的那个。

显然我错过了一些东西,我只是不知道它是什么。

4

1 回答 1

4

It looks to me like you've run into the problem that's discussed in Core Issue 339 as well as N2634. The bottom line is that you're pushing a bit beyond what any compiler can currently handle, even though what you're doing is allowed by the standard. C++ 0x will add more detail about what will and won't result in SFINAE failure versus a hard error. See N3000, §14.9.2, if you want to get into the gory details.

于 2010-01-15T07:02:06.583 回答