我试图为编译器设计一种方法来推断作为非类型模板参数传递的数组的大小。
如果我明确地将数组大小作为第三个模板参数传递,我可以使模板工作,但这会导致该技术出错。
任何人都可以想出一种方法来做到这一点。下面的代码不能编译,但它给出了我想要实现的想法。
// Compile time deduction of array size.
template <typename T, const size_t SIZE>
char(&array_size(T(&array)[SIZE]))[SIZE];
#define ARRAY_SIZE(x) (sizeof(array_size(x)))
template <typename T, T BEGIN[]>
struct Test
{
enum
{
SIZE = ARRAY_SIZE(BEGIN)
};
};
int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int main()
{
Test<int, a> test;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
[编辑] 我忘了指出该解决方案还必须与 C++03 兼容。
想象一下我有这个模板类。
template <typename... TMessageHandler>
class message_handler_set
{
public:
static bool call_handler(const MessageType& command)
{
// Call each TMessageHandler type's 'call_handler' and return the OR of the returns.
}
};
Run Code Online (Sandbox Code Playgroud)
我希望能够call_handler为每种TMessageHandler类型调用静态并返回返回值的 OR。对于三种消息处理程序类型,代码将等同于这个......
template <typename TMessageHandler1, typename TMessageHandler2, typename TMessageHandler3>
class message_handler_set
{
public:
static bool call_handler(const MessageType& command)
{
return TMessageHandler1::call_handler(command) ||
TMessageHandler2::call_handler(command) ||
TMessageHandler3::call_handler(command);
}
};
Run Code Online (Sandbox Code Playgroud)
是否可以使用折叠表达式来实现?