c++ - 编译时函数求值,不完整类型

标签 c++ c++11 template-meta-programming

我有以下模板用于检查类型是否为 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;
}

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

最佳答案

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, "");

关于c++ - 编译时函数求值,不完整类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35875393/

相关文章:

c++ - printf() 和 std::cout 在指针方面的区别

c++ - 用于记录时间戳的不同 C++ 时钟的优缺点是什么?

c++ - C++ 上简单文件处理代码中的模糊错误

c++ - 如何使用 SimpleBlobDetector 获取 blob 的额外信息?

c++ - 如何使用 std::tuple 的值作为参数调用函数?

c++ - 右值和左值的重载函数

c++ - 如何生成具有推导签名的成员函数

c++ - 错误 : call of overloaded distance is ambiguous

c++ - 模板模板参数的参数似乎是非模板类型

c++ - 这个 has_member 类模板是如何工作的?