Uygun enable_if kullanımı ve şablon uzmanlığı konusunda bir sorunla karşılaşıyorum.Şablon uzmanlığı ve enable_if sorunları
#include <type_traits>
#include <iostream>
template <class T,
class = typename std::enable_if<std::is_floating_point<T>::value>::type>
bool less(T a, T b) {
// ....
}
template <class T,
class = typename std::enable_if<std::is_integral<T>::value>::type>
bool less(T a, T b) {
// ....
}
int main() {
float a;
float b;
less(a,b);
return 0;
}
Yukarıdaki kod derleme değil -
I have function called "less" that checks if 1st arg is less than 2nd arg. Let's say I want to have 2 different kinds of implementations depending on the type of input - 1 implementation for integer and another for double.
Ben şimdiye kadar bu gibi görünüyor var kodu:
(gizlilik nedenleriyle) örnek değiştirdikten sonra, burada bir karşılaştırılabilir örnek çünkü - Daha az yöntemi yeniden tanımladığımı söylüyor.
Hatalar şunlardır:
Z.cpp:15:19: error: template parameter redefines default argument
class = typename std::enable_if<std::is_integral<T>::value>::type>
^
Z.cpp:9:19: note: previous default template argument defined here
class = typename std::enable_if<std::is_floating_point<T>::value>::type>
^
Z.cpp:16:11: error: redefinition of 'less'
bool less(T a, T b) {
^
Z.cpp:10:11: note: previous definition is here
bool less(T a, T b) {
^
Z.cpp:23:5: error: no matching function for call to 'less'
less(a,b);
^~~~
Z.cpp:15:43: note: candidate template ignored: disabled by 'enable_if'
[with T = float]
class = typename std::enable_if<std::is_integral<T>::value>::type>
^
3 errors generated.
birisi hata burada neler olduğunu işaret edebilir?
temel olarak, dönüş türünü nasıl çağırdığınızdan dolayı 'enable_if' kullanmıyorsunuz. – Alex
Hızlı çözüm, şablonlardan birine ayrı bir aşırı yük olarak değerlendirilebilmesi için bir elips parametresi '...' eklemektir. – 0x499602D2
Veya imzayı "template :: value> :: type * = nullptr> ' –
vsoftco