C ++:在模板别名中使用static_assert

bre*_*att 2 c++ c++14

可以static_assert与模板别名一起使用吗?我知道如何使用SFINAE与模板的别名,以及如何使用static_assert同一个struct,但我想static_assert用化名给一个更清洁的错误消息。

我想到了以下用例:

#include <array>

constexpr bool is_valid(int n){
    return n <= 10;
}

template <int n>
struct Foo {
    static_assert(is_valid(n), "This class cannot handle more than 10 dimensions");
};

template <int n>
using Bar = std::array<float,n>;  

template <int n, std::enable_if_t<is_valid(n)> * unused = nullptr>
using BarSFINAE = std::array<float,n>;  

int main() {

    Foo<5>();
    // Foo<20>(); // Triggers the compiler-time static_assert

    Bar<5>();
    Bar<20>(); // TODO: Should trigger a compiler-time static_assert

    BarSFINAE<5>();
    // BarSFINAE<20>(); // Not allowed due to SFINAE, but throws an ugly compile time message
}
Run Code Online (Sandbox Code Playgroud)

问题本质上是别名没有主体。所以我不知道该在哪儿放东西static_assert

Sto*_*ica 5

当您正确识别问题时,解决方案是添加一些别名可以依赖的正文。例如,一个功能。

namespace detail {
    template<std::size_t N>
    constexpr auto checked_size() {
        static_assert(is_valid(N), "");
        return N;
    }
}

template <int n>
using Bar = std::array<float, detail::checked_size<n>()>;  
Run Code Online (Sandbox Code Playgroud)