私のプロジェクトの1つに、ヘッダーファイルに次のものがあります。
auto is_base_type = generic_type_test<const type_expression_base>;
auto is_array = generic_type_test<const type_expression_tarray>;
auto is_named_type = generic_type_test<const type_expression_named>;
は次generic_type_test
のように定義されています。
template<typename T>
bool generic_type_test(const type_expression& arg)
{
return generic_test<type_expression, T>(arg);
}
まったく同じヘッダー ファイル内。
コンパイルすると、multiple definition
リンカーエラーが大量に発生します(明らかに)
st_pp.o:ast_pp.cpp:(.data+0x0): multiple definition of `Ast::is_base_type'
st_helper.o:ast_helper.cpp:(.data+0x0): first defined here
問題は、ヘッダー ファイルに宣言を保持しながら、定義を独自のコンパイル ユニット (「.cpp」ファイル) に移動するにはどうすればよいかということです。
ジャロッド42へ
あなたのアイデアを適用すると、結果が得られます。
g++ -o build/ast_helper.o -c --std=c++11 -Isrc -Ibuild build/ast_helper.cpp
build/ast_helper.cpp:11:10: error: conflicting declaration ‘auto Ast::is_base_type’
auto is_base_type = generic_type_test<const type_expression_base>;
^
In file included from build/ast_helper.cpp:1:0:
src/ast_helper.hpp:54:10: error: ‘Ast::is_base_type’ has a previous declaration as ‘bool (* Ast::is_base_type)(const Ast::type_expression&)’
auto is_base_type = generic_type_test<const type_expression_base>;
^
線で;
// Below is line 11 of ast_helper.cpp
auto is_base_type = generic_type_test<const type_expression_base>;
// Below is line 54 of ast_helper.hpp
extern decltype(generic_type_test<const type_expression_base>) is_base_type;
また、最も簡単な修正はフォワード関数であることも知っていますが、この方法での関数ポインターの単純さが本当に気に入っています。