Ben bir işlevi var.C++ fazla türleri için std :: enable_if
Ancak, ben sadece int
için bu işlevi etkinleştirmek gerekiyor ama aynı zamanda float
ve const char *
için ... nasıl aynı yöntem 3x kez yazmadan bunu yapmak? Bunun gibi
Ben bir işlevi var.C++ fazla türleri için std :: enable_if
Ancak, ben sadece int
için bu işlevi etkinleştirmek gerekiyor ama aynı zamanda float
ve const char *
için ... nasıl aynı yöntem 3x kez yazmadan bunu yapmak? Bunun gibi
:
template <typename T,
typename std::enable_if <std::is_same<T, int >::value ||
std::is_same<T, float >::value ||
std::is_same<T, const char *>::value>::type* = nullptr>
void test(T i)
{
//process data
}
C++ 17 için genel bir çözüm (godbolt.org işaretli)
#include <type_traits>
template< typename U, typename ... Ts > struct belong_to
{
// before C++17 value will have to be defined recursively on the head of Ts
static constexpr bool value = (std::is_same< U, Ts >::value || ...);
using type = typename std::enable_if< value, U > ::type;
};
// usage example:
template< typename T >
using testable = typename belong_to< T, int, float, const char >::type;
template< typename T > void test (testable<T> i)
{
// test process
}
int main()
{
test< int > (3);
test< float > (3.0);
test< const char > ('c');
// test< signed char >(1); does not compile!!!
}
başka jenerik çözüm std :: ayırtım (C kullanmaktır ++ 17) mantıksal OR'leri gerçekleştirmek için. İzin verilen tipler, test işlevinize yapılan çağrıda şablon parametreleri olarak belirtilir veya uzmanlaşma için bir yazım hatası tanımlayabilirsiniz.
#include <iostream>
#include <type_traits>
template <typename... Ts, typename T, typename std::enable_if<std::disjunction<std::is_same<T, Ts>...>::value>::type* = nullptr>
void test(T i)
{
std::cout << "test\n";
}
int main()
{
int i = 4;
test<int, float, const char*>(i);
//test<float, const char*>(i); // compile fails since no int
// or use a typedef for the specialization
typedef void (*specialized_t)(int);
constexpr specialized_t test2 = &test<int, float, const char*>;
test2(i);
}
Bir öneri. Muhtemelen, eğer aşırıya kaçanların seçiminde niteleyiciler önemli olmayacaksa, 'remove_cv' denilebilir. –
@YanZhou 'i' parametresi referans olarak geçmediğinden, ancak değere göre, sabitlik ve volatileness yine de kaldırılacaktır. Bu nedenle, 'T' cv-nitelikli olmayacak ve' remove_cv' türüne hiçbir şey yapmayacaktır. –