Note: the following code is illegal, but a conforming compiler is not required to reject it (and some don't).
In a library I'm working with I have a template function declaration for Foo
and a template function definition for Bar
in foobar.h
:
template<class C> int Foo();
template<class C> int Bar() {
return Something( Foo<C>() );
}
The intent is that other code would be able to use it like this:
#include "foobar.h"
int main() {
Bar<MyClass>();
return 0;
}
// Ideally, the usage (above) and the definition (below)
// would/could be in different translation units.
template<> int Foo<MyClass>() { return 5; }
The question: Is there a way to make this work that is also legal?
The issue is (if I'm understanding things correctly) that despite compiling, this is technically illegal: it violates the ODR because both the explicit specialization and the usage of Bar<MyClass>
count as definitions, despite the fact that there is no body to work with in the usage case.
The reasons I want to use this pattern to parameterize Foo
is that, as a result of the style guide I'm required to follow, the only way to ensure that anything is lexically included before the definition of Bar
is for it to be included by foobar.h
. But (for reason I expect I don't need to explain) that's a non-starter.