« first day (2327 days earlier)      last day (530 days later) » 

1:46 AM
hey guys how do I combine two elements in vector? I have say vector [1,2,3], I want to sum 2 and 3 and produce [1,5], how do I do this?
 
2:43 AM
template<typename T, typename U> std::vector<T> foo(T, U){}
How can I tell the complier that U is be equivalent to either std::vector<T> or T.
 
3:20 AM
I found a solution. Any better way to void explicitly declare ` foo<int>` in this simple code snippet?
#include <iostream>
#include <vector>
#include <functional>

template<typename T, typename U, typename = typename std::enable_if<
std::is_same< T, U >::value || std::is_same<std::vector<T>, U>::value>::type>
void foo(std::function<U(void)> func)
{
std::cout << "on the move!\n";
}

int main()
{
foo<int>(std::function<int(void)>());
foo<int>(std::function<std::vector<int>(void)>());
//foo<int>(std::function<float(void)>()); //does not compile, in expectation.
}
 
 
5 hours later…
nwp
7:56 AM
@John Overloading is probably easiest.
1 message moved from Lounge<C++>
@Mahesha999 The example is a bit too simple. int a = vector.back(); vector.pop_back(); vector.back() += a;
That's one way, but maybe you don't always want the last 2 numbers or want all pairs or whatever. There are vector.insert to insert an element at a specific position and vector.erase to remove an element at a specific position.
 
nwp
8:24 AM
@John Hmm, never mind, overloading doesn't work because you can assign an std::function<float()> to a std::function<int()>, so the third line doesn't fail to compile. I guess it doesn't get much easier besides superficial changes like removing the unnecessary voids and using a less ancient compiler and standard that support std::is_same_v.
 
I see. Thank you.
 
8:40 AM
Why `auto func1 = std::bind(do_nothing);
foo<int>(func1); ` does not compile?
Here is the said code snippet.
 
nwp
8:52 AM
Looks like it fails to deduce U. It could be int or float or something else. Somewhat related to why the overload version doesn't do what you want.
foo<int, int>(func1); compiles
 
9:08 AM
Should not func1 would be implicitly converted to the type of std::function<int(void)> since foo<> expects std::function and the gesture of do_nothing is int()?
Whare am I wrong?
 
nwp
It doesn't know you want std::function<int()>. It only knows about std::function<U()> and can't figure out what U should be. It doesn't have to be int.
 
std::function<U()> could not be deduced as int since do_nothing returns int?
 
nwp
No, U could not be deduced as int because float would also work and now it's ambiguous.
It essentially explicitly tells the compiler to use whatever the function returns as the return type for std::function.
 
9:41 AM
Thank you so much. You save me a day!
 

« first day (2327 days earlier)      last day (530 days later) »