我有這樣的代碼,但它不會編譯:爲什麼我不能將繼承的錯誤用作SFINAE?
#include <iostream>
#include <stdexcept>
#include <cassert>
template<class> struct id{};
template< class U, class V> struct base: public id<U>, public id<V>
{
static const bool value = true;
};
template< class U, class V>
struct is_different
{
typedef char (&true_)[1];
typedef char (&false_)[2];
template< class T, class K, bool = base<T,K>::value >
struct checker;
template< class T, class K>
static true_ test(checker<T,K>*);
template< class , class >
static false_ test(...);
static const bool value = sizeof(test<U,V>(0)) == sizeof(true_);
};
int main (void)
{
bool b1 = is_different<int,float>::value;
bool b2 = is_different<int,int>::value; // <--- error
std::cout << std::boolalpha << b1 << '\n'
<< b2 << '\n';
return 0;
}
錯誤:
main.cpp: In instantiation of ‘struct base<int, int>’:
main.cpp:25:17: required by substitution of ‘template<class T, class K> static char (& is_different<U, V>::test(is_different<U, V>::checker<T, K>*))[1] [with T = T; K = K; U = int; V = int] [with T = int; K = int]’
main.cpp:31:41: required from ‘const bool is_different<int, int>::value’
main.cpp:39:38: required from here
main.cpp:7:36: error: duplicate base type ‘id<int>’ invalid
template< class U, class V> struct base: public id<U>, public id<V>
爲什麼我不能使用重複繼承的失敗作爲SFINAE?
我會說,因爲模板參數替換並不必然涉及實例化模板類,這將需要檢測來自相同類型的繼承。 SFINAE將會是不一致的,它是其中的一部分。 – jrok