您可以使用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();
可能的std :: enable_if會幫助你在這種情況下?某種SFINAE解決方案。 –
您需要使用模板專業化。然而,您可能不需要專門研究A的全部內容。您可以有一些小技巧,其中get()在模板類B中。您可以專門化該類,並從中繼承A以獲取函數的預期形式。 – qeadz
[重寫函數模板專用中的返回類型]的可能重複(http://stackoverflow.com/questions/15911890/overriding-return-type-in-function-template-specialization) –