编译器看不到模板专业化?
Compiler doesn't see 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());
}
Class 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 header
#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;
}
输出:
我的 .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());
}
Class 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 header
#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;
}
输出: