I want to write two template functions such that one catches a specific case and the other catches all other cases that don't match first case. I'm trying to use std::enable_if to catch the specific case, but the compiler still fails with an ambiguous match. How can I write these overloaded functions so that the ambiguity is resolved by the compiler? (I'm using g++)
I've tried writing the following code (this is a simplified example that reproduces the problem):
struct resource1_t{
};
struct resource2_t{
};
template <typename R, typename V>
struct unit_t{
typedef R resource_t;
typedef V value_t;
unit_t(value_t const& value):v(){}
value_t v;
value_t calcValue(resource_t const& r)const{return v;}
};
// Specific case (U::resource_t == R)
template <typename U, typename R, typename=std::enable_if_t<std::is_same_v<typename U::resource_t,R>>>
typename U::value_t callCalcValue(U const& u, R const& r){
return u.calcValue(r);
}
// General case (U::resource_t != R)
template <typename U, typename R>
typename U::value_t callCalcValue(U const& u, R const& r){
// Fail immediately!
assert(!"Unit resource does not match");
return U::value_t();
}
int main()
{
// Create an array of unit variants
typedef unit_t<resource1_t,int> U1;
typedef unit_t<resource2_t,float> U2;
std::vector<std::variant<U1,U2>> units;
units.emplace_back(U1(1));
units.emplace_back(U2(1.0f));
// Create a parallel array of resources
std::vector<std::variant<resource1_t,resource2_t>> resources;
resources.emplace_back(resource1_t());
resources.emplace_back(resource2_t());
// Call calcValue for each unit on the parallel resource
for(int i(0); i<units.size(); ++i){
std::visit([&](auto&& unit){
std::visit([&](auto&& resource){
// Fails to compile with substitution failure...
//std::cout << unit.calcValue(resource) << "\n";
// Results in ambiguous call compile error...
std::cout << callCalcValue(unit,resource) << "\n";
},resources[i]);
},units[i]);
}
}
I expected the compiler to match all cases where std::is_same_v<U::resource_t,R>
to the specific case and all other combinations to the general case, instead, the compiler fails saying the function is ambiguous.
I also tried ! std::is_same
for the second definition and the compiler fails with error: redefinition of ... callCalcValue()...