C++11下实现判断函数参数可被指定类型初始化的类型特性
C++11中判断参数可被对象初始化的类型条件
我希望使用可变参数模板重构一个基于Boost_PP的函数接口,该接口用于注册函数对象,伪代码如下:
template<typename F, typename ReturnValue, typename Arg1, ..., typename ArgN, typename Example1, ..., typename ExampleN> void registerFunction(F&& function, std::string parameterName1, std::string parameterDescription1, Example1 e1, ...., std::string parameterNameN, std::string parameterDescriptionN, ExampleN en); float rectangleArea(const float width, const float heigth); registerFunction<float, const float, const float>(&rectangleArea, "width", "width of rectangle", 2, "height", "height of parameter", 4);
我尝试用以下代码替代Boost_PP生成的函数:
template<typename F, typename ReturnValue, typename ... Args, typename ... Description> void registerFunction(F&& function, Description&& ... desc);
但要求每第三个参数需满足:将其转发给function时函数可调用,伪代码示例:
function(std::forward<Description2>(desc2),std::forward<Description5>(desc5),.....)
我尝试使用SFINAE来限制函数仅接受合法的描述参数:
template<typename Args, typename Descriptions, typename Enable = void> struct ParameterParser: std::false_type {}; // recursion end template<typename Enable> struct ParameterParser<std::tuple<>, std::tuple<>, Enable>: std::true_type {}; template<typename Argument, typename ... RemainingArguments, typename Name, typename ParameterDescription, typename Example, typename ... RemainingDescription> struct ParameterParser<std::tuple<Argument, RemainingArguments...>, std::tuple<Name, ParameterDescription, Example, RemainingDescription...>, typename std::enable_if< (sizeof...(RemainingArguments)) * 3 == sizeof...(RemainingDescription) && std::is_convertible<Example, Argument>::value && std::is_convertible<ParameterDescription, std::string>::value && std::is_convertible<Name, std::string>::value>::type> :ParameterParser<std::tuple<RemainingArguments...>, std::tuple<RemainingDescription...>> {}; template<typename ArgumentTuple, typename DescriptionTuple> using ValidDescription = typename std::enable_if<ParameterParser<ArgumentTuple, DescriptionTuple>::value>::type; template<typename ReturnValue, typename ... Args, typename ... Description, typename F, typename = ValidDescription<std::tuple<Args...>, std::tuple<Description...>>> void registerFunction(F&& function, Description&& ... desc) { }
但发现std::is_convertible<Example, Argument>::value并不符合我的需求,问题如下:
void functionToRegister(int&); // this won't compile registerFunction<void, int&>(&functionToRegister, "a parameter", "a description", 1);
这里1被推导为int类型,而std::is_convertible<int, int&>::value为false。
请问在C++11中,如何表达类型ARG和CallOBJ之间的如下条件:函数f(ARG a)的参数a可被CallOBJ类型的对象初始化?
注:我只能使用C++11。
内容的提问来源于stack exchange,提问作者Mehno
相关产品推荐
相关产品推荐

