程序员问答大本营 98sky.com.


10 questions online user: 19

8
votes
answers
6 views
+10

Where to put using directives in C++ header files

For my project I am using some pretty convoluted data structures, e.g.

std::unordered_map<int, std::list<std::shared_ptr<const Foo>>>

for which I would like to declare type aliases for readability. The code on which I built my project on already did this by putting using statements globally in the header files:

// bar.h
#ifndef BAR_H
#define BAR_H

#include <unordered_map>
#include <list>
#include <memory>
#include "foo.h"

using FooTable = std::unordered_map<int, std::list<std::shared_ptr<const Foo>>>;

class Bar {
    FooTable create_foo();
};

#endif

Since my C++ knowledge was a little rusty, I just adopted this style -- but now I read that using using in that way can be problematic, since it forces this alias on everything that includes this header.

Despite a good amount of googling, I could not find a concrete answer on how to handle this properly, only lots of statements on what not to do. So, I just put the using inside the class:

// bar.h
#ifndef BAR_H
#define BAR_H

#include <unordered_map>
#include <list>
#include <memory>
#include "foo.h"


class Bar {
    using FooTable = std::unordered_map<int, std::list<std::shared_ptr<const Foo>>>;

    FooTable create_foo();
};

#endif

However this has the drawback, that I need to restate the alias in the source file:

// bar.cpp
#include "bar.h"

using FooTable = std::unordered_map<int, std::list<std::shared_ptr<const Foo>>>;

FooTable Bar::create_foo()
{
...
}

While this seems to work, I am not sure whether this is safe... and my gut tells me it is kind of ugly. So before I rewrite my whole project like this I thought I'd ask: Is a there a better/more elegant/safer way to do this? Or should I just refrain from using type aliases in header files completely?

10
votes
answers
8 views
+10

Why is this C++ fold expression valid?

On cppreference, I saw that there are four types of fold expressions, unary right, unary left, binary right, and binary left. What is the type of this fold expression here? I'm having a hard time understanding why it is valid.

    template <typename Res, typename... Ts>
    vector<Res> to_vector(Ts&&... ts) {
        vector<Res> vec;
        (vec.push_back(ts) ...); // *
        return vec;
    }

What is the value of "pack", "op" and "init" in line *, if any?

This example is from page 244 of Bjarne Stroustrup's A Tour of C++ book, and seems like a comma was forgotten in the example, hence my confusion.

13
votes
answers
8 views
+10

Why do I get 38528 when casting 10000000 to char?

Java uses 32 bits for the char tipe - so the max value is 65536.

But the following code give me the result reported in the title.

public static void main(String[] args) {
    int a = 10000000;
    char b = 33;
    b = (char)a;
    System.out.println((int)b);

}
12
votes
answers
24 views
+10

Ada - Nullable type

How can I initialize a custom type to null ?

I want to do this :

TestVar : T_MyType := null;

With :

type T_MyType is
record
    field1 : float
    field2 : Boolean
end record

But I have an error :

expected type "T_MyType" defined at myfile.ads

11
votes
answers
4 views
+10

How C structures get passed to function in assembly?

1)How C structures get passed to function in assembly. I mean pass by value, not pass by reference. 2)By the way, how callees return structure to its callers? I'm so sorry for the poor expression since I'm not a native English speaker.

I wrote a simple program to testify how C structures get passed to function. But the result was quite surpirsed. Some value was passed by register, but some value was passed by pushing them into stack. Here is the code.

source code

#include <stdio.h>

typedef struct {
        int age;
        enum {Man, Woman} gen;
        double height;
        int class;
        char *name;
} student;

void print_student_info(student s) {
        printf("age: %d, gen: %s, height: %f, name: %s
", 
                        s.age,
                        s.gen == Man? "Man":"Woman",
                        s.height, s.name);
}

int main() {
        student s;
        s.age = 10;
        s.gen = Man;
        s.height = 1.30;
        s.class = 3;
        s.name = "Tom";
        print_student_info(s);
        return 0;
}

asm

 6fa:   55                      push   %rbp
 6fb:   48 89 e5                mov    %rsp,%rbp
 6fe:   48 83 ec 20             sub    $0x20,%rsp
 702:   c7 45 e0 0a 00 00 00    movl   $0xa,-0x20(%rbp)
 709:   c7 45 e4 00 00 00 00    movl   $0x0,-0x1c(%rbp)
 710:   f2 0f 10 05 00 01 00    movsd  0x100(%rip),%xmm0        # 818 <_IO_stdin_used+0x48>
 717:   00 
 718:   f2 0f 11 45 e8          movsd  %xmm0,-0x18(%rbp)
 71d:   c7 45 f0 03 00 00 00    movl   $0x3,-0x10(%rbp)
 724:   48 8d 05 e5 00 00 00    lea    0xe5(%rip),%rax        # 810 <_IO_stdin_used+0x40>
 72b:   48 89 45 f8             mov    %rax,-0x8(%rbp)
 72f:   ff 75 f8                pushq  -0x8(%rbp)
 732:   ff 75 f0                pushq  -0x10(%rbp)
 735:   ff 75 e8                pushq  -0x18(%rbp)
 738:   ff 75 e0                pushq  -0x20(%rbp)
 73b:   e8 70 ff ff ff          callq  6b0 <print_student_info>
 740:   48 83 c4 20             add    $0x20,%rsp
 744:   b8 00 00 00 00          mov    $0x0,%eax
 749:   c9                      leaveq 
 74a:   c3                      retq   
 74b:   0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)   

I expected structure was passed to function using the stack, but the code above showed it wasn't.

7
votes
answers
6 views
+10

On hover flip the semi-circle

I want to flip the semi-circle on hovering.

.main {
  border: 2px solid green;
  border-radius: 190px;
  height: 200px;
  width: 200px;
}

.btm {
  border-bottom-left-radius: 190px;
  border-bottom-right-radius: 190px;
  background-color: red;
  height: 100px;
}
<div class="main">
  <div style="height: 100px;">
  </div>
  <div class="btm">
  </div>
</div> 

The above code the bottom part of the circle is red colored what I want is just I want to make top part of the circle to be red on hovering.

Any help will be Appreciated.

13
votes
answers
4 views
+10

Return variant from a lambda

I have this simple lambda:

    std::variant<int, char> myLambda = []() { // no suitable user-defined conversion from "type" to "std::variant<int, char>" exists
        std::variant<int, char> res;

        if (true)
        {
            res = 1;
        }
        else
        {
            res = 'c'; 
        }

        return res;
    };

But it doesn't compile, producing error no suitable user-defined conversion from "type" to "std::variant<int, char>" exists. What am I doing wrong?

12
votes
answers
8 views
+10

JavaScript map & find at the same time: findMap?

How would you rewrite this without using a for loop?

const a = [2, 5, 78, 4];
const expensiveFunction = n => 2 * n;

let result;

// Find the first number 
for (let i = 0; i < a.length; i++) {
    const r = expensiveFunction(a[i]);

    if (r > 100) {
        result = r;
        break;
    }
}

console.log(result);

My naive approach:

const result = a.map(expensiveFunction).find(x => x > 100);
console.log(result);

But this runs expensiveFunction on all the elements, which I would like to avoid. In the above case, we should avoid running expensiveFunction(4).

Some languages have find_map (e.g, Rust), I didn't find it in lodash nor in underscore.

11
votes
answers
20 views
+10

Possible to use Promise.in with infinite time?

Is there a direct way to use Promise.in (or other sub/method/class) to achieve an indefinite amount of time? In other words the Promise is never resolved.

Currently I'm checking the $time when the promise is kept to see if an indefinite time was requested (indicated by negative or 0 value) and preventing the react block from exiting.

Is isn't a terrible solution, but is there are more idiomatic way of achieving this?

my $time=0;
react {
    whenever Promise.in($time) {
          #check if time is 0
          done if $time > 0;
    }
    whenever signal(SIGINT) {
        done;
    }

    #whenever Supply...{
    #}
}
12
votes
answers
10 views
+10

How could rust multiply &i32 with i32?

Consider this example:

fn main() {
    let v: Vec<i32> = vec![1, 2, 3, 4, 5];
    let b: i32 = (&v[2]) * 4.0;
    println!("product of third value with 4 is {}", b);
}

This fails as expected as float can't be multiplied with &i32.

error[E0277]: cannot multiply `{float}` to `&i32`
 --> srcmain.rs:3:23
  |
3 |   let b: i32 = (&v[2]) * 4.0;
  |                        ^ no implementation for `&i32 * {float}`
  |
  = help: the trait `std::ops::Mul<{float}>` is not implemented for `&i32`

But when I change the float to int, it works fine.

fn main() {
    let v: Vec<i32> = vec![1, 2, 3, 4, 5];
    let b: i32 = (&v[2]) * 4;
    println!("product of third value with 4 is {}", b);
}

Did the compiler implement the operation between &i32 and i32? If yes, how is this operation justified in such a type safe language?