2016-04-14 6 views
0

1)CPPソースファイル内のテンプレートクラスからメソッド実装:* .cppファイルにテンプレートの特殊化メソッドを実装する方法は?

//foo.hppを

template<typename T> 
class foo 
{ 
public: 
    void bar(const T &t); 
}; 

//foo.cpp

template <class T> 
void foo<T>::bar(const T &t) 
{ 
    std::cout << "General." << std::endl; 
} 

template class foo<int>; 

//メイン

foo<int> foo; 

foo.bar(42); 

2)CPPソースファイルのクラスからテンプレート化されたメソッドを実装する:

//foo.hpp

class foo 
{ 
public: 
    template<typename T> 
    void bar(const T &t); 
}; 

//foo.cpp

template <class T> 
void foo::bar(const T &t) 
{ 
    std::cout << "General." << std::endl; 
} 

template void foo::bar<int>(const int &t); 

//メイン

foo toto; 

toto.bar<int>(42); 

3)専門的なテンプレートメソッドを実装しますか...?

//foo.hpp

class foo 
{ 
public: 
    template<typename T> 
    void bar(const T &t); 
    template<> 
    void bar<float>(const float &t); 
}; 

//foo.cpp

template <class T> 
void foo::bar(const T &t) 
{ 
    std::cout << "General." << std::endl; 
} 


template <> 
void foo::bar<float>(const float &t) 
{ 
    std::cout << "Float specialization." << std::endl; 
} 

template void foo::bar<int>(const int &t); 
template void foo::bar<float>(const float &t); //Seems to be not correct! 

//メイン

foo toto; 

toto.bar<float>(42); 

//コンパイルエラー:

error LNK2019: unresolved external link "public: void __thiscall foo::bar<float>(float const &)" ([email protected]@[email protected]@[email protected]) referenced in _main function 

私はこの問題の解決策には達しません。

ご協力いただきありがとうございます。

+1

がいhttp://stackoverflow.com/questions/495021/why-can-templates-をonly-be-in-the-header-fileはここには適用されません。 – fritzone

答えて

0

あなたの宣言が間違っている、それは次のようになります。

class foo 
{ 
public: 
    template<typename T> 
    void bar(const T &t); 
}; 

とのcppファイルに:

template <class T> 
void foo::bar(const T &) 
{ 
    std::cout << "General." << std::endl; 
} 

template <> 
void foo::bar<float>(const float &) 
{ 
    std::cout << "Float specialization." << std::endl; 
} 

template void foo::bar<int>(const int &); 
+0

ご助力ありがとうございます!さようなら。 – user1364743

関連する問題