0

下面的代码没问题:

template <class T>
std::enable_if<std::is_atomic<T>::value, bool>
foo(T t) { return true; }

template <class T>
std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }

int main(void){
  foo(1);  // return true
  auto std::vector<int> a{2};
  foo(a);  // return false
}

但是当我使用一个类来捆绑它们时,它无法编译:

template <class T>
class test {
public:

std::enable_if<std::is_atomic<T>::value, bool>
foo(T t) { return true; }

std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }
};

int main(...) {
  test<int> obj;
  obj.foo(1);
  test<std::vector<int>> obj2;
  std::vector<int> tmp{2};
  obj2.foo(tmp);
}

铿锵++打印:

error: functions that differ only in their return type cannot be overloaded

所以我写了一些东西来欺骗编译器(在第二个中添加一个 S foo):

template <class S>
std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }

它仍然无法工作:

error: no type named 'type' in 'std::enable_if<false, bool>'

我怎样才能让它在课堂上工作?

4

3 回答 3

1

您忘记在enable_if之后添加::type :(请参阅enable_if

template <class T> std::enable_if<std::is_atomic<T>::value, bool>::type
foo(T t) { return true; }
于 2013-11-07T06:14:26.473 回答
0

两个成员函数都应该有不同的模板参数(以下可以正常工作)

template <class T>
class test {
public:

template<typename U>
typename std::enable_if<std::is_atomic<U>::value, bool>::type
foo(U t) { return true; }

template<typename U>
typename std::enable_if<tmp::is_sequence<U>::value, bool>::type
foo(U t) { return false; }

};
于 2013-11-07T05:58:28.053 回答
0

如果你真的想做你正在做的事情,经典的习惯用法是引入一个带有默认值的假 SFINAE 参数:

bool foo(T t, std::enable_if<..., void*> = nullptr) { ... }
于 2013-11-07T06:06:42.073 回答