I am trying to implement a C++ template meta function that determines if a type is callable from the method input arguments.
i.e. for a function void foo(double, double)
the meta function would return true
for callable_t<foo, double, double>
, true
for callable_t<foo, int, int>
(due to compiler doing implicit cast) and false
for anything else such as wrong number of arguments callable_t<foo, double>
.
My attempt is as follows, however it fails for any function that returns anything other than void and I can't seem to fix it.
I am new to template reprogramming so any help would be appreciated.
#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;
}
I am using a compiler that supports C++ 14.
Aucun commentaire:
Enregistrer un commentaire