私は次の問題に取り組もうとしています:if
ステートメントを実行したいのですが、テンプレートの引数が特定のオブジェクトであるか、そうでない場合は、オブジェクトのメンバー関数を呼び出します。のは、私がstd::string
std :: is_sameを使用してifステートメントでクラスメンバーにアクセス
スニペットをしたいとしましょう:
#include <iostream>
#include <string>
template <typename T>
void is_string(const T& arg) {
if (std::is_same<T, const std::string&>::value)
std::cout << arg.length() << std::endl;
else
std::cout << "The argument is not a string" << std::endl;
}
int main() {
is_string(0);
return 0;
}
それは次のエラーで、コンパイルされません。
types.cpp: In instantiation of ‘void is_string(const T&) [with T = int]’:
types.cpp:13:13: required from here
types.cpp:7:13: error: request for member ‘length’ in ‘arg’, which is of non-class type ‘const int’
std::cout << arg.length() << std::endl;
私は私が達成しようとしていることはないかもしれないことを数えますC++ 11では可能ですが、そのようなことをする方法についていくつか提案していただきたいと思います。