Próbuję zaimplementować funkcję meta szablonu C++, która określa, czy typ jest wywoływalny z argumentów wejściowych metody.Funkcja meta C++, która określa, czy typ można wywoływać dla podanych argumentów.
czyli dla funkcji void foo(double, double)
funkcja meta wróci true
dla callable_t<foo, double, double>
, true
dla callable_t<foo, int, int>
(ze względu na kompilator robi niejawna cast) i false
do niczego innego, takiego jak niewłaściwej liczby argumentów callable_t<foo, double>
.
Moja próba jest następująca, jednak nie działa dla żadnej funkcji, która zwraca coś innego niż nieważne i nie mogę tego naprawić.
Jestem nowicjuszem w przeprogramowywaniu szablonów, więc każda pomoc będzie mile widziana.
#include <iostream>
#include <type_traits>
#include <utility>
#include <functional>
namespace impl
{
template <typename...>
struct callable_args
{
};
template <class F, class Args, class = void>
struct callable : std::false_type
{
};
template <class F, class... Args>
struct callable<F, callable_args<Args...>, std::result_of_t<F(Args...)>> : std::true_type
{
};
}
template <class F, class... Args>
struct callable : impl::callable<F, impl::callable_args<Args...>>
{
};
template <class F, class... Args>
constexpr auto callable_v = callable<F, Args...>::value;
int main()
{
{
using Func = std::function<void()>;
auto result = callable_v<Func>;
std::cout << "test 1 (should be 1) = " << result << std::endl;
}
{
using Func = std::function<void(int)>;
auto result = callable_v<Func, int>;
std::cout << "test 2 (should be 1) = " << result << std::endl;
}
{
using Func = std::function<int(int)>;
auto result = callable_v<Func, int>;
std::cout << "test 3 (should be 1) = " << result << std::endl;
}
std::getchar();
return EXIT_SUCCESS;
}
Używam kompilatora, który obsługuje C++ 14.
Co z 'callable_t'? –
NathanOliver
@NathanOliver, wszelkie argumenty, które kompilator mógłby wydedukować są wywoływalne (aczkolwiek z ostrzeżeniem) powinny być prawidłowe, więc 'callable_t' byłoby ok, jeśli 'foo' jest zdefiniowane jako say' foo (int, int) 'lub' foo (double, double) 'lub' foo (float, float) ', ale nie' foo (custom_type, custom_type) 'gdzie' custom_type' nie może zostać przekonwertowane. –
keith
@Marco A. Niestety nie :-( – keith