虽然仍在学习基于模板的元编程,但我遇到了以下问题:
我有一个模板使用类型别名,我想用static_assert
缩小允许的类型,但我不知道如何写它:
using service_func_plain_loop_t = std::function<void(void)>;
using service_func_with_arg_loop_t = std::function<void(std::string)>;
using service_callbacks_t = std::map<event, std::function<bool(void) >>;
template<typename service_loop> using service_functionality_t =
std::pair<service_loop, service_callbacks_t>;
static_assert(
std::is_convertible<service_loop,service_func_plain_loop_t>.value ||
std::is_convertible<service_loop,service_func_with_arg_loop_t>.value,
"service_loop has to be either service_func_plain_loop_t or "
"service_func_with_arg_loop_t");
此方法失败,因为service_loop
未在static_assert
的范围内声明。在检查类时,我可以将断言移到类范围中,但这里的语法是什么?
答案 0 :(得分:1)
您可以编写一个帮助程序类来执行static_assert
:
template <typename service_loop>
struct service_functionality {
static_assert(
std::is_convertible<service_loop,service_func_plain_loop_t>::value ||
std::is_convertible<service_loop,service_func_with_arg_loop_t>::value,
"service_loop has to be either service_func_plain_loop_t or "
"service_func_with_arg_loop_t");
using type = std::pair<service_loop, service_callbacks_t>;
};
template<typename service_loop> using service_functionality_t =
typename service_functionality<service_loop>::type;
另请注意,它应为std::is_convertible<T,U>::value
或std::is_convertible<T,U>{}
而不是std::is_convertible<T,U>.value
。虽然我们可能会在C ++ 17中获得std::is_convertible_v<T,U>
辅助变量模板。