另一個通用的解決方案是使用std ::析取(C++ 17)以執行邏輯或。允許的類型在調用測試函數時被指定爲模板參數,或者你可以爲專門化定義一個typedef。
#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);
}
run the code
一個建議。如果限定符在重載的選擇中無關緊要,可能可以使用'remove_cv'。 –
@YanZhou由於參數'i'不是通過引用傳遞的,而是通過值,常量和volatile將被移除。因此,'T'不會被cv限定,'remove_cv'不會對該類型做任何事情。 –