我有一个Painter
模板类与paint()
模板功能。我正在使用标记专门化模板类中的模板函数。 我已经将Painter.h
中的模板函数paint()
的定义和Painter.cpp
中的函数重载。暧昧模板专业化
当我在Painter.cpp
中明确实例化paint()
时,出现编译器错误。 我的要求是我需要在Painter.cpp文件中实现重载函数paint(ColorTag<Color::RED>)
。
源文件如下:
Painter.h
#include <iostream>
enum class Color {
RED = 0,
GREEN = 1,
BLUE = 2
};
template<Color>
struct ColorTag {
};
template<typename T>
class Painter {
public:
template<Color MyColor>
void paint(ColorTag<MyColor>);
void paint(ColorTag<Color::RED>);
};
template<typename T>
template<Color MyColor>
void Painter<T>::paint(ColorTag<MyColor>){
std::cout << "General" << std::endl;
}
Painter.cpp
#include "Painter.h"
template<typename T>
void Painter<T>::paint(ColorTag<Color::RED>){
std::cout << "RED" << std::endl;
}
template void Painter<int>::paint(ColorTag<Color::RED>);
Main.cpp的
#include "Painter.h"
int main(){
Painter<int> painter;
painter.paint(ColorTag<Color::RED>());
return 0;
}
使用
g++ Main.cpp Painter.cpp -std=c++11
我获得以下编译器错误,当我明确实例paint()
在Painter.cpp编译
Painter.cpp:8:15: error: ambiguous template specialization ‘paint<>’ for ‘void Painter<int>::paint(ColorTag<(Color)0>)’
template void Painter<int>::paint(ColorTag<Color::RED>);
^
Painter.cpp:4:6: note: candidates are: void Painter<T>::paint(ColorTag<(Color)0>) [with T = int]
void Painter<T>::paint(ColorTag<Color::RED>){
^
In file included from Painter.cpp:1:0:
Painter.h:20:10: note: template<Color MyColor> void Painter<T>::paint(ColorTag<MyColor>) [with Color MyColor = MyColor; T = int]
void paint(ColorTag<MyColor>);
我已经试过
首先我创建了一个模板函数n调用instantiatePaint()
来调用paint()
函数。然后我在Painter.cpp
文件中放置并实例化它。这工作。但这种感觉很尴尬。
template<typename T>
template<Color MyColor>
void Painter<T>::instantiatePaint(ColorTag<MyColor>){
paint(ColorTag<MyColor>());
}
template void Painter<int>::instantiatePaint(ColorTag<Color::RED>);
其次搬重载函数定义从Painter.cpp
到Painter.h
。这工作,但打破了我的要求paint(ColorTag<Color::RED>)
在Painter.cpp
超载功能。
有没有更好的方法来解决这个问题,究竟是什么导致了模糊性?
请你回答,你都非常相信,这将100%的工作,“不知道”使得冒险 – piyushj
因为我没有检查它GCC,我读的地方双模板是编译器相关的。 – Jai