2015-10-08 69 views
2

我上課是這樣的:模板類不同的返回類型取決於類的參數

template<class T> 
class A{ 
    // lots of methods here 

    Something get(); 
}; 

我想Something get()成爲const Something &get()如果T是特定的類。

首先我試着用繼承來做,但它太亂了。

我可以這樣做,不需要專門整個class A,也不需要引入第二個模板。

+1

可能的std :: enable_if會幫助你在這種情況下?某種SFINAE解決方案。 –

+1

您需要使用模板專業化。然而,您可能不需要專門研究A的全部內容。您可以有一些小技巧,其中get()在模板類B中。您可以專門化該類,並從中繼承A以獲取函數的預期形式。 – qeadz

+0

[重寫函數模板專用中的返回類型]的可能重複(http://stackoverflow.com/questions/15911890/overriding-return-type-in​​-function-template-specialization) –

回答

5

你只需用簡單易用的英語語言寫下來。

std::conditional<std::is_same<T, SpecificClass>::value, 
       Something const&, 
       Something>::type get(); 
2

您可以使用std::conditional像由N.M.解釋,或者,如果你需要,你可以使用std::enable_if方法不同的行爲:

struct Something { }; 

template<typename T> 
class Foo 
{ 
    Something something; 
public: 
    template<typename U = T, typename std::enable_if<!std::is_same<U, float>::value, int>::type = 0> Something get() { 
    std::cout << "not specialized called" << std::endl; 
    return something; 
    } 

    template<typename U = T, typename std::enable_if<std::is_same<U, float>::value, int>::type = 0> const Something& get() { 
    std::cout << "specialized called" << std::endl; 
    return something; 
    } 
}; 


Something sm1 = Foo<float>().get(); 
Something sm2 = Foo<int>().get();