這是C++ 11中extern模板的正確用法嗎? (也可以是,extern template class
和各自template class
是在同一個翻譯單元可見?)模板類和相同的翻譯單元中的各自的extern模板類
// example.hpp:
#pragma once
template< typename T >
class C {
void f(T);
};
// question is about the next two lines
extern template class C<float>;
extern template class C<double>;
// example_def.hpp:
#include "example.hpp"
template< typename T >
void C<T>::f(T) {
//... smth. practicable
}
// example.cpp:
#include "example_def.hpp"
template class C<float>;
template class C<double>;
// other.hpp:
#pragma once
void g();
// other.cpp:
#include "other.hpp"
#include "example.hpp"
// maybe those two lines should be here instead?
void g() {
C<float>();
C<double>();
}
// main.cpp:
#include "example.hpp"
#include "other.hpp"
// ...and here?
int main() {
C<float>();
C<double>();
g();
return 0;
}
最後一段包含的信息不明顯。你確定這是事實嗎? – Orient
@Dukales:我不完全確定你具體提到哪些信息,但我相信最後一段是正確的。你可以聲明一個模板化的函數,而不是爲編譯器提供一個隱式實例化的定義,並且可以通過在定義可見的翻譯單元中顯式實例化來解析結果未解析的符號(我認爲它們甚至可以通過隱式實例化來自另一個翻譯單元,但我認爲在這種情況下依靠隱式實例太脆弱)。 –