注意:以下代码是非法的,但不需要符合要求的编译器拒绝它(有些则不需要)。
在我正在使用的库中,我有一个模板函数声明Foo
和一个模板函数定义Bar
in foobar.h
:
template<class C> int Foo();
template<class C> int Bar() {
return Something( Foo<C>() );
}
目的是其他代码可以像这样使用它:
#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; }
问题: 有没有办法使这项工作也合法?
问题是(如果我理解正确的话)尽管编译,这在技术上是非法的:它违反了ODR,因为明确的专业化和使用Bar<MyClass>
count 作为定义,尽管事实上没有实体可以使用用例。
我想使用此模式进行参数化的原因Foo
是,由于我必须遵循样式指南,确保在定义之前以词法方式包含任何内容的唯一方法是Bar
将其包含在foobar.h
. 但是(出于我希望我不需要解释的原因)这不是首发。