我想实现一个C++模板元函数,确定是否可从方法输入参数调用类型。C++元函数,确定是否可供调用提供的参数类型
即一个函数void foo(double, double)
元函数会为callable_t<foo, int, int>
(由于编译器做隐式转换)和false
为别的返回true
为callable_t<foo, double, double>
,true
如错误的参数个数callable_t<foo, double>
。
我的尝试如下,但它失败的任何函数返回除void以外的任何东西,我似乎无法修复它。
我是新来的模板重新编程,所以任何帮助,将不胜感激。
#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;
}
我使用的是支持C++ 14
怎么样'callable_t'? –
NathanOliver
@NathanOliver,编译器推断的任何参数都可以被调用(虽然有警告)应该是有效的,所以如果foo被定义为foo(int,int),那么'callable_t int)'或'foo(double,double)'或'foo(float,float)'而不是'foo(custom_type,custom_type)',其中'custom_type'不能被隐含转换。 –
keith
@Marco答:可悲的是:-( – keith