我的 .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.
#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;
}
输出:
关于c++ - 编译器看不到模板特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49120595/