c++ - 无权访问模板模板参数

标签 c++ templates

为什么我不能这样做:

template<template<class E>class Derived>
struct X
{
    static void f()
    {
        Derived<E>::value;
    }
};

我遇到的问题是我无法编译此代码,因为我收到一条错误消息,指出参数 E 尚未声明。有没有办法让我可以使用或不使用这个形式参数?

最佳答案

模板模板参数的参数不获取参数,因此通常没有名称。部分特化是这条规则的异常(exception)。试试这个:

template<class> // Derived<E> is only only parameter
struct X; // but you actually need two parameters, Derived and E

template< template <class> class Derived, class E >
struct X< Derived< E > > // so use partial specialization.
{
    static void f()
    {
        Derived<E>::value; // only reason to want this is to
        Derived<int>::value; // use different specializations
    }
};

当然,如果你不需要重新专攻Derived< something_else > , 忽略 Derived<E> 的事实是模板特化:

template<class Derived>
struct X
{
    static void f()
    {
        Derived::value;
    }
};

X< my_class< something > > my_x; // a specialized class template is a class

关于c++ - 无权访问模板模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4293365/

相关文章:

c++ - JSONCPP 附加到文件

C++ STL 容器中的 NULL 指针

c++ - 来自 c++11 的 std::thread 问题

c++ - 无法在没有显式范围的情况下访问模板基类的静态成员

c++ - 通过 C++ 实现容器元素总和的模板函数

C++ std::find() 和模板参数

c++ - 将 glm::vec3 与 boost 多精度 float 相乘

c++ - 使用 OpenCV 从图像中检测最大矩形

c++ - std::function 的类型推导

c++ - 如何解释模板函数调用的 gcov 结果