質問

以下のコードは大丈夫です:

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);
}

Clang ++印刷:

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

だから私はコンパイラにチートする何かを書きます(2番目に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>'

クラスで機能させるにはどうすればよいですか?

役に立ちましたか?

解決 2

どちらのメンバーファンクションも異なるテンプレートパラメーターを持っている必要があります(フォローはOKに動作します)

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; }

};

他のヒント

追加するのを忘れました ::タイプenable_if: : (見る enable_if)

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

あなたが本当にしていることを本当にやりたいなら、古典的なイディオムは、デフォルトの値で偽のsfinae引数を導入することです。

bool foo(T t, std::enable_if<..., void*> = nullptr) { ... }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top