C++ 转换问题

标签 c++ c++11 g++ clang

我尝试使用以下方法编译这个 (--std=c++0x):

  • [FAIL with --std=c++0x flag] clang version 3.2-1~exp9ubuntu1 (tags/RELEASE_32/final)(基于 LLVM 3.2)
  • [FAIL without --std=c++0x flag] clang version 3.2-1~exp9ubuntu1 (tags/RELEASE_32/final)(基于 LLVM 3.2)
  • [FAIL without --std=c++11 flag] Apple LLVM version 5.0 (clang-500.2.79)(基于 LLVM 3.3svn)
  • [FAIL with --std=c++11 flag] Apple LLVM version 5.0 (clang-500.2.79)(基于 LLVM 3.3svn)
  • [使用 --std=c++0x 标志通过] gcc 版本 4.7.3 (Ubuntu/Linaro 4.7.3-1ubuntu1)
  • [没有 --std=c++0x 标志的失败] gcc 版本 4.7.3 (Ubuntu/Linaro 4.7.3-1ubuntu1)

当它在 clang ubuntu 处失败时,会产生以下错误:

test.cpp:26:37: error: no viable conversion from 'const P' to 'timeval'
        return static_cast<timeval>(_p);
                                    ^~
/usr/include/x86_64-linux-gnu/bits/time.h:30:8: note: candidate constructor
      (the implicit copy constructor) not viable: no known conversion from 'const P' to
      'const timeval &' for 1st argument
struct timeval
       ^
/usr/include/x86_64-linux-gnu/bits/time.h:30:8: note: candidate constructor
     (the implicit move constructor) not viable: no known conversion from 'const P' to 'timeval &&' for
      1st argument
struct timeval
       ^
test.cpp:9:5: note: candidate function
    operator const timeval() const {
    ^
test.cpp:13:5: note: candidate function
    operator const int8_t() const {
    ^

我不确定我做错了什么。

#include <iostream>
#include <cstdint>

union P {
    timeval _timeval;
    int8_t  _int8_t;
    uint8_t _uint8_t;

    operator const timeval() const {
        return _timeval;
    }

    operator const int8_t() const {
        return _int8_t;
    }
};


struct Y {

    operator const int8_t() const {
        return static_cast<int8_t>(_p);
    }

    operator const timeval() const {
        return static_cast<timeval>(_p);
    }

    P _p;
};

int main()
{

    Y testobj;
    timeval ret = static_cast<timeval>(testobj);
    return 0;
}

最佳答案

作为起点,您缺少 #include 开头的 #

#include <iostream>
#include <cstdint>

您也没有包含任何应该定义类型 timeval 的 header 。鉴于您显然正在使用的系统,您可能想要:

#include <sys/time.h>

如果您使用的是 Windows,那可能是:

#include <winsock2.h>

可能还有更多问题,但这至少应该让您在正确的总体方向上开始。

关于C++ 转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19814638/

相关文章:

c++ - 如何使用具有 pair<int,int> vector 元素的 unordered_set

c++ - 读写迭代器 - C++

c++ - 在 C++ 中读取内存时出现段错误

c++ - 优化标志导致计算不正确

c++ - 条件变量 "miss"可以通知调用吗?

c++ - 让 vim 的 YouCompleteMe 插件识别 exuberant-ctags

c++ - std::thread 在无限循环中的随机时间后锁定

c++ - Valgrind 为同一个应用程序提供不同的内存泄漏

c++ - SFINAE 示例不清楚

c++ - 如何使用 eigen 编译 C++ 程序而不指定 -I 标志?