(I don't understand the root cause yet so the title may not be correct.)
I have the following c++ code which does not compile:
#include <iostream>
#include <memory>
#include <vector>
#include <variant>
#include <optional>
template <typename T>
class A {
public:
~A() = default;
std::unique_ptr<int> ptr = nullptr;
};
template <typename T>
class B : public A<std::vector<T>> {
public:
static B<T> Create() {
return B<T>();
}
};
using AllTypes = std::variant<B<int64_t>, B<uint64_t>, B<double>>;
std::optional<AllTypes> Get() {
// Error! No viable conversion!
return B<int64_t>::Create();
}
The error message is:
main.cpp: In function ‘std::optional<std::variant<B<long int>, B<long unsigned int>, B<double> > > Get()’:
main.cpp:34:28: error: could not convert ‘B::Create() [with T = long int]()’ from ‘B’ to ‘std::optional, B, B > >’
34 | return B<int64_t>::Create();
| ~~~~~~~~~~~~~~~~~~^~
| |
| B<long int>
The error can be reproduced here: https://onlinegdb.com/2H-K9x0kq.
but if I remove the unique ptr variable ptr
, it can correctly compile. And if I move the ptr member to the child class B
it also compiles.
Can anyone give some hints on what is wrong? Right now I don't know what keywords/rules to search for. Many thanks!
Update:
- I changed the original absl::StatusOr to std::optional instead. I feel the errors might be because of the same problem.