SPM*_*PMP 2 c++ template-meta-programming c++11
我有以下模板来检查是否有类型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;
}
Run Code Online (Sandbox Code Playgroud)
Clang错误:
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
Run Code Online (Sandbox Code Playgroud)
Clang是正确的,因为正如它所说,在完成定义之前,类型是不完整的.我想如果你打开-pedantic然后你也会在gcc中遇到错误.
一个更简单的方法来做你想要的只是使用std::is_same:
#include <string>
#include <type_traits>
static_assert(std::is_same<std::string, std::string>::value, "");
static_assert(not std::is_same<std::string, int>::value, "");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
192 次 |
| 最近记录: |