2012-02-09 22 views
1

はここにここに私のテンプレート関数テンプレート関数がコンパイルされません

template<typename T> std::stringstream logging_expansion (T const * value){ 
    std::stringstream retval; 
    retval = retval << *value; 
    return retval; 
} 

である私はそれを

logging_expansion("This is the log comes from the convinient function"); 

を使用するようにそれを呼び出す方法です。しかし、リンカは、関数を参照することができないことを私に語っています:

Undefined symbols for architecture x86_64: 
    "std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >  logging_expansion<char>(char const*)", referenced from: 
    _main in WirelessAutomationDeviceXpcService.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 
+1

私は文字通り 'return(std :: stringstream()<< * value);'を一行に書くことができると思います。 –

答えて

5

ヘッダーファイルにテンプレート関数の実装を提供するか、またはその中の特殊化を定義する必要がありますader。

//header.h 

template<typename T> std::stringstream logging_expansion (T const * value){ 
    std::stringstream retval; 
    retval = retval << *value; 
    return retval; 
} 
+0

これをコンパイルしようとすると、コンパイラのエラーが発生します。それにかかわらず、あなたがリンク段階に達するなら、これはそれを行うべきです。 –

+0

ああ、ありがとう。私はそれがコピー可能ではないので、私はstringstreamをコピーしようとしている私のコードにいくつかのエラーがあると思う。とにかく、元の問題は解決されました。私はすべてのテンプレート定義をヘッダファイルに入れる必要があります。 –

+0

@NegativeZeroええ、それはテンプレートの仕組みです。コンパイラーは、最初に遭遇したときに各特殊化用のコードを生成するので、同じ翻訳単位内のコードにアクセスする必要があります。 –

0

あなたのコードと間違っていくつかのものがあります: *

//header.h 
template<typename T> std::stringstream logging_expansion (T const * value); 

//implementation.cpp 
#include "header.h" 

template<typename T> std::stringstream logging_expansion (T const * value){ 
    std::stringstream retval; 
    retval = retval << *value; 
    return retval; 
} 

//main.cpp 
#include "header.h" 

//.... 
logging_expansion("This is the log comes from the convinient function"); 
//.... 

だからあなたはヘッダに実装を移動する必要があります。

私はあなたが現在のようなものを持っていると仮定しています文字列の最初の文字をストリームに追加するつもりはないと思います *valueはあまり意味がありません

  • stringstreamに代入演算子またはコピーコンストラクタがありません したがってretval = retval << *valueも意味をなさないものです。

テンプレート機能が不足している一般的な原因は、テンプレートを.cppファイルでインスタンス化するのを忘れたことです。あなたはこのようにします

template std::stringstream logging_expansion<char>(char const *value); 
関連する問題