I've spent the past ~week developing a type-agnostic logging system for a game engine, and I'm using type traits to control how different template arguments should be recorded. Union and class types are ignoring those checks (somehow) and triggering error C2679.
I'd like to know why this might be happening and what I can do to fix it besides breaking my template down into lots of small functions.
if (std::is_arithmetic<loggableType>::value)
{
if (destination == DESTINATIONS::CONSOLE)
{
*printStreamPttr << "logging " << typeid(loggableType).name() << " with value " << dataLogging << '\n';
ConsolePrinter::OutputText(printStreamPttr);
}
else
{
logFileStream.open(logFilePath);
logFileStream << "logging " << typeid(loggableType).name() << " with value " << dataLogging << '\n';
logFileStream.close();
}
}
if
does not cause a compile-time branch. Both branches must be valid regardless of the result of the condition.Here is my
dispatch
function I find useful in these cases:This utility function does compile-time dispatching between a set of options.
Here is an example:
dispatch( std::is_arithmetic<decltype(b)>{} )
takes a truthy or falsy type by value (actually any number of them). It finds the first truthy type passed to it.It then returns a lambda that takes any number of arguments, and returns the one corresponding to the first truthy argument to dispatch. If dispatch has no truthy arguments, it pretends it had a truthy argument "after the end" and dispatches based on that.
As
bob
is notis_arithmetic
, this is a falsy type. So dispatch will return a lambda returning its second argument.In this case we pass it two lambdas, both with the same signature.
We are going to return the 2nd one.
We then pass it
b
. The first lambda, which expects the value to be passed toostream&::operator<<
, is never evaluated, so the fact thatunion bob
doesn't support it doesn't matter.live example, and using MSVC2015.
The above is valid C++14, and I believe I avoided all of the MSVC foibles that prevent it from compiling it.
To pass a type into your lambdas, you might want to use these:
then your code looks like: