Reputation: 125
Say I have the following struct
template <int size>
struct Foo
{
...
int GetValue()
{
if (size == 1)
{
return -3;
}
return 4;
}
};
This seems a bit wasteful since size
is known at compile time. What I would like to do is something like this
template <int size>
struct Foo
{
...
// Should be used if size is 1
int GetValue()
{
return -3;
}
// Should be used if size is not 1
int GetValue()
{
return 4;
}
};
I assume there is a way to do this but I don't know how.
Upvotes: 0
Views: 139
Reputation: 218323
In C++17, you might use if constexpr
to avoid suntime branching (which might be optimized anyway):
template <int size>
struct Foo
{
// ...
int GetValue()
{
if constexpr (size == 1)
{
return -3;
}
return 4;
}
};
Upvotes: 3