Reputation: 3388
I'm unsure if what I want to do is possible in C++, so asking here.
I have a templated class MyClass
that has an optional template argument idx
. I have another non-templated class OtherClass
. What I want to do is to do some sort of overload resolution based on idx
:
If idx
is provided (has a value other than -1), I want to call the templated version of OtherClass::otherMethod
.
Otherwise, I want to call the non-templated version of OtherClass::otherMethod
.
Note that if T==SomeType
the user of MyClass
would provide idx
. In other cases, no idx
is needed. Also, the two different versions of OtherClass::otherMethod
are guaranteed to take different input types. Seems to me that I somehow need to disable overload resolution for OtherClass::otherMethod<>
when idx == -1
and enable it only if idx!= -1
.
The code below outlines what I have:
template <typename T, int32_t idx=-1>
class MyClass
{
OtherClass m_other;
void myMethod(T arg)
{
// If idx == -1
// m_other.otherMethod<idx>(arg);
// else
// m_other.otherMethod(arg);
}
}
class OtherClass
{
template<int32_t idx>
void otherMethod(SomeType arg)
{
// Some operation that depends on idx
}
void otherMethod(YetAnotherType arg)
{
}
}
EDIT:
One obvious solution is to template void otherMethod(YetAnotherType arg)
with some default (and unused) argument. I'm looking for solutions other than that.
EDIT2: (in response to comments)
I'm using C++11. A simple if
doesn't always work, as demonstrated here. Thus, I need to know whether what I need to do is possible with compile-time constructs.
Upvotes: 0
Views: 68
Reputation: 52621
Something along these lines, perhaps:
template <typename T, int32_t idx=-1>
class MyClass {
OtherClass m_other;
void myMethodHelper(T arg, std::true_type) {
m_other.otherMethod<idx>(arg);
}
void myMethodHelper(T arg, std::false_type) {
m_other.otherMethod(arg);
}
public:
void myMethod(T arg) {
myMethodHelper(arg, std::integral_constant<bool, (idx >= 0)>{});
}
};
Upvotes: 1