c++ - 编译器看不到模板特化?

标签 c++ c++11 templates template-specialization

我的 .h 中有模板文件:

template <typename T>
void addToolsAreaItem(){
    T* item = new T(_image, this);
    doSpecifiedStaff<T>(item);
    _tools.addTool(item);
}

及其在 .cpp 方面的特化文件:

template <>
void ImageWorkspace::addToolsAreaItem<Preview>(){
    _preview = std::make_unique<QGraphicsView>(_splitter);
    _imagesLayout.addWidget(_preview.get());
}

Prewiew为空,仅用于一种情况的特殊行为(切换预览按钮时)。

但是我得到编译器错误:

imageworkspace.h:45: error: new initializer expression list treated as compound expression [-fpermissive]
     T* item = new T(_image, this);
               ^~~~~~~~~~~~~~~~~~~

imageworkspace.h:45: error: no matching function for call to ‘Preview::Preview(ImageWorkspace*)’
     T* item = new T(_image, this);
               ^~~~~~~~~~~~~~~~~~~

编译器是否看到特化?如何解决?

函数称为 addToolsAreaItem<Preview>()来自资源。

最佳答案

You need a forward declaration for the specialization in the header file. Otherwise, other translation units can't see it.

Henri Menke

#include "Image.h"
int main()
{
    Image::addToolsAreaItem<int>();
    system("pause");
}

Image.h 头文件

#pragma once    
#include <iostream>

namespace Image{

    template <typename T>
    void addToolsAreaItem();

    // forward declaration
    template <>
    void addToolsAreaItem<int>();

}

cpp:

#include "Image.h"

template <typename T>
void Image::addToolsAreaItem()
{
    std::cout << typeid(T).name() << std::endl;
}

template <>
void Image::addToolsAreaItem<int>()
{
    std::cout << "Spec: int " << std::endl;
}

输出:

enter image description here

关于c++ - 编译器看不到模板特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49120595/

相关文章:

c++ - 如何为 boost::bind 强制模板函数重载?

c++ - 为什么 vector 返回会丢失一些值?

c++ - 检查对象是否是基于基类的子类的实例

c++ - 使用模板模板参数时是否需要显式列出默认参数?

c++ - 为模板特化初始化静态常量

C++ 随机数没有改变

c++ - OpenMp - 每个线程的循环/数组边界

c++ - 关于 C++ 中的仿函数

c++ - 使用 C++11 时出现错误 "Error: stray character"

c++ - lambda 运算符重载?