从一些元编程代码开始:
template<class... Ts>
class list {}; //a generic container for a list of types
template<class in_list_type>
class front //get the type of the first template parameter
{
template<template<class...> class in_list_less_template_type, class front_type, class... rest_types>
static front_type deduce_type(in_list_less_template_type<front_type, rest_types...>*);
public:
typedef decltype(deduce_type((in_list_type*)nullptr)) type;
};
此代码适用于此:
typedef typename front<list<int, float, char>>::type type; //type is int
但是当第一项是函数类型时编译失败:
// no matching function for call to 'deduce_type'
typedef typename front<list<void (), float, char>>::type type;
我目前只能访问 XCode,无法确认这是否只是一个 XCode 错误。我正在使用 XCode 4.5.1,使用 Apple LLVM 编译器 4.1。
最佳答案
当模板参数为 deduce_type
正在推导,front_type
有void()
作为候选人。然而,这将使 deduce_type
有类型 void ()()
(函数返回一个函数 -- alias<void()>()
如果您假设 template<typename T> using alias = T;
在范围内)。这是一个错误,类型推导失败。
一个解决方案是 deduce_type
返回类似 identity<front_type>
的内容, 和 type
成为 typename decltype(deduce_type((in_list_type*)nullptr))::type
的别名.
关于c++ - 为什么类型推导在(非指针)函数类型上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12943525/