小编Ice*_*Pic的帖子

虚函数并转换为void和back

目前我正在使用传统的c ++代码库.在此代码库中,指向对象的指针将转换为void-pointers,然后存储在c-library中.请考虑以下代码:

class interface {
public:
  virtual void foo() {
    std::cout << "Interface" << std::endl;}
  virtual ~interface(){};
};

class debug_interface: public interface {
public:
  virtual void foo() {
   std::cout << "Debug Interface" << std::endl;}
};
Run Code Online (Sandbox Code Playgroud)

对象interfacedebug_interface在堆上分配,地址存储在void指针中.在某些时候,指针被检索,然后再转换回基类interface.然后调用虚函数调用.看到

int main(int argc, char *argv[]){

    void *handle = reinterpret_cast<void*>(new interface());
    void *debug_handle = reinterpret_cast<void*>(new debug_interface());

   //void *handle = new interface();
   //void *debug_handle = new debug_interface();

   interface *foo1 = reinterpret_cast<interface*>(handle);
   interface *foo2 = reinterpret_cast<interface*>(debug_handle);

   //interface *foo1 = static_cast<interface*>(handle);
   //interface …
Run Code Online (Sandbox Code Playgroud)

c++ virtual void static-cast reinterpret-cast

8
推荐指数
1
解决办法
1059
查看次数

std ::期货和例外

给出以下源代码

#include <thread>
#include <future>
#include <iostream>
#include <string>
#include <chrono>

int main() {

    auto task = std::async(std::launch::async, [] {       
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        throw std::runtime_error("error");
    });


    try {
        while (task.wait_for(std::chrono::seconds(0)) !=std::future_status::ready)
        {
            std::cout << "Not ready: " << std::endl;
        }
        task.get();
    }
    catch (const std::exception& e)
    {
        std::cout << "Valid: " << task.valid() << std::endl;
    }

}
Run Code Online (Sandbox Code Playgroud)

我希望,该计划将回应Valid: 0.使用g ++ 6.2.0就是这种情况.但是,使用MS VS2015版本14.0.25431.01 Update 3时,响应为Valid: 1.将异常传播到主线程后,未来的状态不会失效.这是一个错误还是我在这里遇到了未定义的行为?

c++ multithreading exception std-future

6
推荐指数
1
解决办法
649
查看次数

Variadic模板和Alexandrescu元组实现

我尝试学习一些关于模板元编程的知识,目前我正在使用可变参数模板.

在他的演讲"Variadic模板是Funadic"中,Alexandrescu引入了一个小元组实现,我尝试构建并可能延伸一点.(我知道这是一个玩具的例子,我只是想学习更多关于c ++的知识).但是,我的代码有一个小问题.

这里是:

template <typename... Ts> 
class tuple
{};

template<size_t, typename> struct tuple_element;

template<typename T, typename... Ts>
struct tuple_element<0, tuple<T, Ts...>> 
{
    typedef T type;
};

template <size_t k, typename T, typename... Ts>
struct tuple_element<k, tuple<T, Ts...>> 
{
    typedef 
       typename tuple_element<k-1,tuple<Ts...>>::type type;
};

template<size_t k, typename... Ts>
typename std::enable_if<k == 0, 
                        typename tuple_element<0,tuple<Ts...>>::type&>::type
   get(tuple<Ts...>& t)
{return t.head_;}

template<size_t k, typename T, typename... Ts>
typename std::enable_if<k != 0,
                        typename tuple_element<k,tuple<T,Ts...>>::type&>::type
   get(tuple<T,Ts...>& t)
{
    tuple<Ts...> & super = t;
    return get<k-1>(super); …
Run Code Online (Sandbox Code Playgroud)

c++ variadic-templates

5
推荐指数
1
解决办法
834
查看次数