简体   繁体   English

如何优化可变参数模板专业化?

[英]How to optimize variadic template specializations?

Suppose you have the following struct to concatenate two templated structs:假设您有以下结构来连接两个模板化结构:

/// concat.hpp
template<typename...>
struct concat_struct;

// concat_specialization.hpp
template<std::size_t... m, std::size_t... n>
struct concat_struct<$CLASSNAME<m...>, $CLASSNAME<n...>>
{
    using type = $CLASSNAME<m..., n...>;
};

template<typename a, typename b>
using concat = typename concat_struct<a, b>::type;

I can now do我现在可以

#include "concat.hpp"
#define $CLASSNAME MyClass
#include "concat_specialization.hpp"
#undefine $CLASSNAME
#define $CLASSNAME MyOtherClass
#include "concat_specialization.hpp"

As is, this could easily lead to conflicts, if I were to include "concat_specialization.hpp" again.事实上,如果我再次包含“concat_specialization.hpp”,这很容易导致冲突。 What is the C++ way, to handle multiple specializations of variadic templates?什么是 C++ 方式来处理可变参数模板的多个专业化?

You don't need to explicitly write out a specialization for each $CLASSNAME .您不需要为每个$CLASSNAME明确写出专门化。 You can just add a template template parameter to the specialization, and this will get deduced automatically:您只需将模板模板参数添加到专业化中,这将自动推导出:

template<template<std::size_t...> typename C, std::size_t... m, std::size_t... n>
struct concat_struct<C<m...>, C<n...>>
{
    using type = C<m..., n...>;
};

Here's a demo这是一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM