模板参数涉及模板参数

Lor*_*one 2 c++ templates c++11

在部分专业化的模板参数中使用模板参数时,有没有办法解决标准的限制?我想让它工作的代码是这样的:

template<typename L, size_t offset, typename enable_if< (offset<sizeof(L)), int >::type =0>
class a{};

template<typename L>
class a<L, sizeof(L)-1>{};
Run Code Online (Sandbox Code Playgroud)

ken*_*ytm 5

由于它是 C++11,您可以简单地static_assert用于泛型条件。对于这sizeof(L)-1件事,您需要使用enable_if 技巧,因为它需要专门的东西。例子:

#include <cstdlib>
#include <type_traits>
#include <cstdio>

template <typename L, size_t offset, typename = void>
class a
{
    static_assert(offset < sizeof(L), "something's wrong");
public:
    void f()
    {
        printf("generic\n");
    }
};

template <typename L, size_t offset>
class a<L, offset, typename std::enable_if<offset == sizeof(L)-1>::type>
{
    // note: the static_assert is *not* inherited here.
public:
    void f()
    {
        printf("specialized\n");
    }
};

int main()
{
    static_assert(sizeof(int) == 4, "oops");
    a<int, 3> x;
    a<int, 2> y;
    x.f();
    y.f();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

演示:http : //ideone.com/D2cs5