相关疑难解决方法(0)

为什么不允许非类型参数中的部分特化使用嵌套模板参数

我有这个代码

template<int N, bool C = true>
struct A;

template<int N>
struct A<N, !(N % 5)> {
  /* ... */
};

// should work
A<25> a;
Run Code Online (Sandbox Code Playgroud)

也就是说,对于N可被整除的数字,5编译器应使用部分特化.但编译器不会接受部分特化,因为标准要求它拒绝这样的代码,其中部分特化的非类型参数引用参数而不仅仅是一个参数(比如,A<N, N>是有效的).但是这样做的原因是什么?

请注意,我可以简单地将我的代码更改为更罗嗦的示例,它是有效的

template<bool> struct wrap;
template<int N, typename = wrap<true> >
struct A;

template<int N>
struct A<N, wrap<!(N % 5)> > {
  /* ... */
};

// should work
A<25> a;
Run Code Online (Sandbox Code Playgroud)

这很好,因为它不再是非类型参数.但是,规范禁止更直接的部分专业化的原因是什么?

c++ partial-specialization design-rationale

36
推荐指数
1
解决办法
3802
查看次数

C++ constexpr:在编译时计算std数组

我想将"数组"转换bool为整数序列.所以我需要std::array在编译时计算一个.

这是我的代码

#include <array>

template<typename InputIt, typename T >
inline constexpr typename std::iterator_traits<InputIt>::difference_type
count( InputIt first, InputIt last, const T &value ) {
    typename std::iterator_traits<InputIt>::difference_type ret = 0;
        for (; first != last; ++first) {
            if (*first == value) {
                ret++;
            }
        }
        return ret;
}

template<bool ..._values>
struct keep_value {
    static constexpr std::size_t numberOfValues = sizeof...(_values);
    static constexpr bool values[] = {_values...};
    static constexpr std::size_t numberToKeep = count(values, values + numberOfValues, true);

    static constexpr std::array<std::size_t, …
Run Code Online (Sandbox Code Playgroud)

c++ template-meta-programming variadic-templates constexpr c++14

8
推荐指数
1
解决办法
2485
查看次数