私のテンプレートでは、型名が基本型かどうかに基づいて、さまざまなコード部分が必要です。
このコードをコンパイルすると、MSVC で C4067 が返されます (プリプロセッサ ディレクティブに続く予期しないトークン - 改行が必要です):
template <typename T>
void MyClass<T>::foo()
{
// ... some code here
#if std::is_fundamental<T>::value
if(m_buf[j] < m_buf[idx_min])
idx_min = j;
#else
const ASSortable& curr = dynamic_cast<ASSortable&>(m_buf[j]);
const ASSortable& curr_min = dynamic_cast<ASSortable&>(m_buf[idx_min]);
// error checking removed for simplicity
if(curr.before(curr_min))
idx_min = j;
}
#endif
テンプレートは、プリミティブ データ型と独自の (ASSortable から派生した) データ型の両方で動作し、テンプレートのインスタンス化コードからエラーがスローされます。
template class MyClass<char>;
プリコンパイラ式をこれに変更しようとしてもうまくいきませんでした:
#if std::is_fundamental<T>::value == true
同じ正確な警告を生成します。
このコードを警告なしにする方法はありますか?
編集頭に浮かぶもう1つのことは、これをランタイムチェックに変換し、「定数if式」警告を受け入れることです...特殊化も余分な肥大化もなしに、単一の関数でこれをエレガントに行う方法は本当にありませんか? ?
編集#2したがって、これを解決する方法(これは明らかでしたが、どういうわけか私を逃れました...)はbool ASSortable::operator<(const ASSortable& _o) const {return this->before(_o);};
、仕事をしてコードをきれいにする a を定義することでした(もう一度)。
if
コード内にs や#ifdef
s などの混乱はもうありません。
こんなに明白でシンプルな答えがあったので、私がその質問をしたとは信じられません:(