2015-04-07 96 views
0

我試圖做的模板函數重載一些,下面是例子超載未定義類型

do_something.h

template<typename T> 
void do_something(T const &input){/*....*/} 

void do_something(std::string const &input); 

void do_something(boost::container::string const &input); 

到目前爲止,一切都很好,但如果我想重載什麼一個非定義類型?

像使用類型some_type在頭文件中沒有定義

void do_something(some_type const &input); 

我想使用這樣的

的main.cpp

#include "do_something.h" 
#include "some_type.h" 

#include <boost/container/string.hpp> 

int main() 
{ 
    do_something(std::string("whatever")); 
    do_something(boost::container::string("whatever")); 

    //oops, some_type() never defined in the header file, this 
    //function will call the template version, but this is not 
    //the behavior user expected 
    do_something(some_type()); 
} 

由於some_type不是一個POD ,而不是一個std :: string,boost :: container :: string.I我想我可以設計一個特性來做一些編譯時檢查

template<typename T> 
typename boost::enable_if<is_some_type<T>::value, T>::type 
do_something(T const &input){//.....} 

但是我有更好的方法去做嗎?

我需要編譯時類型檢查,所以我使用template.All調用此函數的類型將根據不同的類型做類似的工作,所以我更喜歡重載。我不需要保存狀態,所以我更喜歡函數而不是階級。 希望這可以幫助你更多地瞭解我打算做什麼。謝謝

+0

我不確定,你可以在模板中使用static_assert嗎? –

回答

3

但是如果我想重載一個非定義的類型呢?

你需要調用do_somethingsome_type類型的對象之前提供的

void do_something(some_type const &input); 

聲明。否則,將使用模板版本。

#include "do_something.h" 
#include "some_type.h" 

// This is all you need. You can implement the function here 
// or any other place of your choice. 
void do_something(some_type const &input); 

#include <boost/container/string.hpp> 

int main() 
{ 
    do_something(std::string("whatever")); 
    do_something(boost::container::string("whatever")); 

    //oops, some_type() never defined in the header file, this 
    //function will call the template version, but this is not 
    //the behavior user expected 
    do_something(some_type()); 
}