I have defined var_t
to be of type std::variant< Fum<Bazz>, Fum<Ack> >
. The templated class Fum<>
should forward its constructor arguments to Bazz and Ack, so it can create them emplace. However, I get the following error:
[g++ default #1] error: no matching conversion for functional-style cast
#include <iostream>
#include <variant>
#include <string>
// Bazz
// C'tor takes in float
struct Bazz {
float f;
Bazz(float)
{
std::cout << "Bazz Main" << std::endl;
}
};
// Ack
// C'tor takes in std::string
struct Ack {
std::string str;
Ack(std::string strParam)
:str(strParam)
{
std::cout << "Ack Main" << std::endl;
}
};
// Fum<>
// Variadic C'Tor should forward args to value of type T
template<typename T>
class Fum {
public:
T value;
template<typename ... Params>
Fum<T>(Params&& ... argsForT)
:value(std::forward<Params>(argsForT)...)
{std::cout << "FUM C'TOR" << std::endl;}
};
typedef std::variant< Fum<Bazz>, Fum<Ack> > var_t;
// Fum forwards string to Ack as expected and creates Ack emplace.
int main() {
Fum<Ack>(std::string("Hello, World!"));
}
// >>>> Ack Main C'Tor
// >>>> Fum C'Tor
int main() {
var_t((std::string("Hello, World!")));
}
// [g++ default #1] error: no matching conversion for functional-
// style cast
I believe Fum
templated C'Tor is causing ambiguity. Therefore, var_t does not know if it should construct Fum<Ack>
or Fum<Bazz>
. But I'm not sure. So how can I fix this?
std::variant
has a proper overload for emplace constuction .
In particular:
template< class T, class... Args >
constexpr explicit variant(std::in_place_type_t<T>, Args&&... args);
So your code could be fixed with:
var_t(std::in_place_type<Fum<Ack>>, std::string("Hello, World!"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.