小编JWe*_*ove的帖子

C++ 模板数组大小推导

我试图为编译器设计一种方法来推断作为非类型模板参数传递的数组的大小。

如果我明确地将数组大小作为第三个模板参数传递,我可以使模板工作,但这会导致该技术出错。

任何人都可以想出一种方法来做到这一点。下面的代码不能编译,但它给出了我想要实现的想法。

// 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 兼容。

c++ arrays templates

3
推荐指数
1
解决办法
4845
查看次数

有没有办法使用 C++17 折叠表达式来实现这一点?

想象一下我有这个模板类。

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)

是否可以使用折叠表达式来实现?

c++ expression fold c++17

2
推荐指数
1
解决办法
69
查看次数

标签 统计

c++ ×2

arrays ×1

c++17 ×1

expression ×1

fold ×1

templates ×1