我有以下模板來檢查類型是否爲std::string
。它在GCC上編譯得很好,但在Clang上失敗。哪一個是正確的行爲?有沒有辦法讓它在兩個方面都有效?上鏘編譯時函數評估,不完整類型
#include<iostream>
#include<string>
#include<type_traits>
using namespace std;
template <typename T> //Checks if T is string type, by testing for the existence of member type "traits_type"
class is_string
{
public:
template<typename C> std::false_type test(...);
template<typename C> std::true_type test(decltype(sizeof(typename C::traits_type)));
enum {
value = decltype(((is_string<T>*)nullptr) -> test<T>(sizeof(0)))::value
};
};
int main() {
cout<<is_string<string>::value<<endl;
}
錯誤:
trial.cpp:15:51: error: member access into incomplete type 'is_string<std::basic_string<char> >'
value = decltype(((is_string<T>*)nullptr) -> test<T>(sizeof(0)))::value
^
trial.cpp:20:7: note: in instantiation of template class 'is_string<std::basic_string<char> >' requested here
cout<<is_string<string>::value<<endl;
^
trial.cpp:8:7: note: definition of 'is_string<std::basic_string<char> >' is not complete until the closing '}'
class is_string
有什麼奇怪的方法來檢查,如果一個類型是的std :: string ...... – SergeyA
我看到現在。元編程還很新穎。 – SPMP