我想在boost中使用enable_if做模板專門化,但無法讓它工作,並且不知道如何編寫它以及語法實際上意味着什麼。我讀過增強文檔,但仍然對我來說不太合理如何使用enable_if和模板專業化C++?
我有四種方法,我希望所有的命名都相同,都非常相似。我有兩個函數將返回一個字符串和兩個函數,將返回一個整數。 在每種情況下,參數都是int,int,返回類型或int,const char *,返回類型,因爲最後一個參數將是可以返回的默認值。
所以這樣的事情...
int getVal(int,int,int)
int getVal(int,const char*,int)
string getVal(int,int,string)
string getVal(int,const char*,string)
但是這不會起作用,因爲參數是相同的,只有返回類型不同,我需要它是一個模板方法,而只是一個重載的方法。這是在一個非模板類。所以我需要enable_if如果返回類型是一個字符串或一個int,或者可能檢查最後一個參數enable_if?
任何幫助,將不勝感激,如果有人能夠解釋什麼語法的意思,並且實際上做,這也會有所幫助。由於
這是很多嘗試我在得到正確的語法嘗試之一..
template<typename myType>
typename enable_if<boost::is_arithmetic<myType>, myType>::type
GetValue(int row, int col, myType d)
{
unsigned int columnIndex = this->GetColumnIndex(col);
try {
CheckColumnType(col, Integer);
}
catch(DatatableException e){
return d;
}
if("0" == this->m_rows[row][col])
{
return 0;
}
else if("1" == this->m_rows[row][col])
{
return 1;
}
else
{
return atoi(this->m_rows[row][col].c_str());
}
}
template<typename myType>
typename disable_if<boost::is_arithmetic<myType>, myType>::type
GetValue(int row, int col, myType d)
{
unsigned int columnIndex = this->GetColumnIndex(col);
try {
CheckColumnType(col, String);
}
catch(DatatableException e){
return d;
}
return this->m_rows[row][col];
}
template <class T>
T GetValue(int row, typename enable_if<is_arithmetic<!T> >::type* dummy = 0){
{
unsigned int columnIndex = this->GetColumnIndex(col);
try {
CheckColumnType(col, Integer);
}
catch(DatatableException e){
return d;
}
if("0" == this->m_rows[row][col])
{
return 0;
}
else if("1" == this->m_rows[row][col])
{
return 1;
}
else
{
return atoi(this->m_rows[row][col].c_str());
}
}
template <class T>
T GetValue(int row, typename enable_if<is_arithmetic<T> >::type* dummy = 0){
try {
CheckColumnType(col, Integer);
}
catch(DatatableException e){
return d;
}
if("0" == this->m_rows[row][col])
{
return 0;
}
else if("1" == this->m_rows[row][col])
{
return 1;
}
else
{
return atoi(this->m_rows[row][col].c_str());
}
}
我很困惑。哪些函數抱怨擁有相同的參數類型?我可以看到具有不同參數類型的四個函數。 – Chowlett
目前尚不清楚實際問題是什麼。 (int,int,int)','(int,const char *,int)','(int,int,string)',' (int,const char *,string)' – Rost
我的要求是使用一個模板函數,如果我想添加其他函數採用相同的參數但返回一個布爾值或日期值,那麼會有問題。 – Bullsfan127