c++ - 派生类的模板特化问题

标签 c++ templates

当我编译以下内容时

#include <iostream>

#define XXX 1
#define YYY 2

class X
{
public:

    template< int FLD >
    void func();
};

template<> void X::func< XXX >()
{
    std::cout << "X::func< " << XXX << " >" << std::endl;
}

class Y : public X
{
public:
};

template<> void Y::func< YYY >()
{
    std::cout << "Y::func< " << YYY << " >" << std::endl;
}

template<> void Y::func< XXX >()
{
    std::cout << "Y::func< " << XXX << " >" << std::endl;
}

int main( int c, char *v[] )
{
    X x;

    Y y;
}

我明白了

x.cpp:24: error: template-id 'func<2>' for 'void Y::func()' does not match any template declaration
x.cpp:24: error: invalid function declaration
x.cpp:29: error: template-id 'func<1>' for 'void Y::func()' does not match any template declaration
x.cpp:29: error: invalid function declaration

我正在尝试在基类中专门化模板。

任何人都可以解释它是如何完成的或者为什么我不能这样做。

谢谢 马克。

最佳答案

您不能这样做,因为您也不能执行以下操作,出于同样的原因,Y::func 未在 Y 中声明:

class X {
public: 
   void foo();
};
void X::foo() {}
class Y : public X {
};
void Y::foo() {}

关于c++ - 派生类的模板特化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3477174/

相关文章:

c++ - C++中的通用迭代器

c++ - 重载 == 函数

c++ - 如何在 Particle (Spark) 的本地构建中包含第三方库?

c++ - 删除间接指针是否正确

c++ - 为什么编译器无法用文字确定 std::max 的模板?

wordpress - 更新后 WP-Admin 中的 Javascript 失败

c++ - for 循环初始化中的 auto 和 decltype

c++ - 将 boost 日期初始化为公元元年

c++ - 常见数据类型的长度是多少?

c++ - MIPS 和 x86_64 之间对象对齐的差异