0

Recently, I have been reading source codes of boost::any, I found that std::any can work fine in a virtual template member function where templates are forbidden. So, I tried to replace templates with std::any to implement template<typename T, typename K> auto add(T a, K b) { return a + b; } just with std::any.

Sadly, I failed.

Here is what I tried (it can only receive (int a, int b) and can't receive real any type, so it is a failure):

auto sum_any(std::any a, std::any b)
{
    return std::any_cast<int>(a) + std::any_cast<int>(b);
}

I hope to see your implementations.

Thanks in advance.

Edit:

template<typename T, typename K>
auto sum_any(std::any a, std::any b)
{
    return std::any_cast<T>(a) + std::any_cast<K>(b);
}

the codes above con't pass compile:

'auto sum_any(std::any,std::any)': could not deduce template argument for 'T'('K')

Chen Li
  • 4,824
  • 3
  • 28
  • 55
  • Looks to me like you have hard coded type `int` with your `std::any_cast<>`. Normally this would be done with a `template` and then use `std::any_cast`. When you can say "can't reveal real `any` type" do you mean you are getting a compiler error or what? If a compiler error what is the message? – Richard Chambers Aug 03 '17 at 14:44
  • @RichardChambers In fact, I have tried std::any_cast and get error, so I didn't post it here. – Chen Li Aug 03 '17 at 14:47
  • Right, because as the error message says, it can't deduce T and K from the argument list. You have to provide them yourself `sum_any(a, b)`. – Simple Aug 03 '17 at 15:08
  • 3
    @czxyl: `any` is not a substitute for templates. It exists to shepherd a value between two places, such that the giver and the receiver both know what type it is, but the code in-between does not. That's what it is for. – Nicol Bolas Aug 03 '17 at 15:16

0 Answers0