這裏是一個可能的解決方案(因爲C++ 11的工作 - 好,它的工作原理與C++ 14,但它與C++ 11做的,如果你使用Base<T>
,而不是auto
作爲返回類型爲f
) :
#include<utility>
#include<type_traits>
template<class T>
class Base{ };
template<class T>
class OtherRandomClass{ };
template<class T, class Other>
class Derived :
public virtual Base<T>,
public virtual OtherRandomClass<Other>
{ };
template<typename T>
constexpr auto f(const Base<T> &b) { return b; }
template<typename T>
struct S {
using type = decltype(f(std::declval<T>()));
};
int main() {
static_assert(std::is_same<typename S<Derived<int, double>>::type, Base<int>>::value, "!");
}
如果Derived
繼承比Base
一次它不工作。
使用sfinae(類似於void_t
成語),甚至可以設計一個類似於enable_if
的類:它只有在T
實際上從Base
繼承一次時才具有type
。
這將有以下形式:
template<typename T>
constexpr auto f(const Base<T> &b) { return b; }
template<typename...>
using void_t = void;
template<typename T, typename = void_t<>>
struct S { };
template<typename T>
struct S<T, void_t<decltype(f(std::declval<T>()))>> {
using type = decltype(f(std::declval<T>()));
};
這個結構可以在編譯時對任何模板欺騙你能想象的使用。
在這兩種情況下,S::type
(如果存在)是Derived
繼承的基類的類型,即Base<T>
。
有關詳細信息,請參見main
函數中的static_assert
。
你可以簡單地在Derived中提供一個'typedef'。 –
@ Cheersandhth.-Alf這是真實的....但我懶惰,不想重寫一噸代碼(所有想法可能是我倒退) – DarthRubik
另一種方法是編譯所有可能的' T'類型。更多的工作。 –