I'd like to create a C++11 function that has two variants (one for enum Row and one for enum Column) without repeating the source code and have the compiler optimize each variant to not include a branch to differentiate the two.
Here is my current cut at this:
namespace {
enum class Orientation
{
Row,
Column
};
template < Orientation orientation >
bool isColumns(Orientation);
template <>
bool isColumns< Orientation::Row >(Orientation)
{
return false;
}
template <>
bool isColumns< Orientation::Column >(Orientation)
{
return true;
}
template < class Orient >
int
findInfo(const Orient orientation)
{
int result = 0;
const bool columns = isColumns(orientation);
// Do a bunch of computation for result.
if (columns) { // This condition to be optimized away by compiler.
// Special case code here only for columns.
}
// More computation for result.
return result;
}
int
test()
{
return findInfo(Orientation::Row) + findInfo(Orientation::Column);
}
}
This does not compile because of template error:
test.cu(27): error: no instance of function template "<unnamed>::isColumns" matches the argument list
argument types are: (const <unnamed>::Orientation)
detected during instantiation of "int <unnamed>::findInfo(Orient) [with Orient=<unnamed>::Orientation]"
(43): here
I do not wish to explicitly specialize findInfo() for Row and Column as that defeats my goal of not repeating the source code visible to the programmer for the two cases.
How can I express this properly and is there a simpler or cleaner way to have the two variants expressed in a single template function?
Aucun commentaire:
Enregistrer un commentaire