Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用带有静态断言的类型别名缩小模板中允许的类型_C++_Templates_C++11_Static Assert - Fatal编程技术网

C++ 使用带有静态断言的类型别名缩小模板中允许的类型

C++ 使用带有静态断言的类型别名缩小模板中允许的类型,c++,templates,c++11,static-assert,C++,Templates,C++11,Static Assert,在学习基于模板的元编程时,我遇到了以下问题: 我有一个使用类型别名的模板,我想用static\u 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 = s

在学习基于模板的元编程时,我遇到了以下问题: 我有一个使用类型别名的模板,我想用
static\u 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\u func\u plain\u loop\u t=std::function;
使用带有参数循环的服务函数t=std::function;
使用服务调用\u t=std::map;
使用服务功能的模板=
std::pair;
静态断言(
std::值是否可转换||
std::是可转换的值,
“服务循环必须是服务函数普通循环或”
“带有参数循环的服务函数”;

此方法失败,因为
服务\u循环
未在
静态\u断言
的范围内声明。在检查类时,我可以将assert移动到类范围中,但是这里的语法是什么?

您可以编写一个helper类来执行
静态\u 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::是否可转换::值||
std::是否可转换::值,
“服务循环必须是服务函数普通循环或”
“带有参数循环的服务函数”;
使用type=std::pair;
};
使用服务功能的模板=
typename服务功能::type;
还请注意,它应该是
std::is_convertable::value
std::is_convertable{}
,而不是
std::is_convertable.value
。尽管我们可能会在C++17中获得
std::is_可转换\u v
helper变量模板


我不太明白。你的意思是说,用不能转换为这些类型的东西实例化
服务功能\u t
,会很难失败吗?@TartanLlama确实如此