【发布时间】:2017-04-13 13:14:15
【问题描述】:
我正在尝试实现一个 C++ 模板元函数,该函数确定一个类型是否可以从方法输入参数中调用。
即对于函数void foo(double, double),元函数将返回true for callable_t<foo, double, double>,true for callable_t<foo, int, int>(由于编译器执行隐式转换)和false 对于其他任何事情,例如错误数量的参数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<foo, float, float>呢? -
@NathanOliver,编译器推断的任何参数都是可调用的(尽管带有警告)应该是有效的,所以如果
foo被定义为foo(int, int)或 @,callable_t<foo, float, float>就可以了987654335@ 或foo(float, float)但不是foo(custom_type, custom_type)其中custom_type不能被隐式转换。 -
@Marco A. 遗憾的是:-(
-
@keith (edited msg) 如果你的编译器也支持一些 C++17 特性,我推荐 is_callable。否则here's a hackish fix for your code。请注意,此代码有许多缺陷,例如完全避免 is_convertible 转换和模板参数格式正确。
-
@Marco A,谢谢,我已经尝试过了,但是在这里查看std::void_t,我的 c++ 14 编译器似乎对简单的 void_t 定义有问题。在链接中使用建议的 void_t 实现使您的示例可以在我的编译器上运行!为了学习,我很想听到更多关于我的代码中的缺陷的信息。我正处于进入 TMP 之旅的开始阶段。
标签: c++ c++11 c++14 template-meta-programming