我有一個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