2016-04-14 17 views
0

1) CPP kaynak dosyası bir şablonu sınıfından yöntemleri uygulamak:Şablon uzmanlık yöntemleri * .cpp dosyalarında nasıl uygulanır?

//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>; 

// ana

foo<int> foo; 

foo.bar(42); 

2) Bir CPP kaynak dosyasındaki bir sınıftan şablon uygular:

//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); 

// ana

foo toto; 

toto.bar<int>(42); 

3) uzman templated yöntemini uygulamak ...?

//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! 

// ana

foo toto; 

toto.bar<float>(42); 

// Derleme hatası:

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

Bu soruna çözüm bulamıyorum.

Yardımlarınız için şimdiden çok teşekkürler.

+1

mu http://stackoverflow.com/questions/495021/why-can-templates- sadece-uygulanan-içinde-başlık dosyası burada geçerli değil mi? – fritzone

cevap

0

Sen bildirimi yanlış, bu olmalıdır:

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

Ve cpp dosyasında:

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

Tamam! Yardımın için çok teşekkürler! Hoşçakal. – user1364743

İlgili konular