在我的例子中,我有一個類Foo<T>
。在我的函數test
中,我需要獲取Foo
的模板參數,否則爲正常類型。首先,我開始使用std::conditional
,但忘記模板參數必須全部有效,無論選擇哪一個。是爲non-Foo
類型創建類型專業化的唯一方法嗎?訪問類型成員
#include <type_traits>
template <typename TYPE>
class Foo
{
public:
using M = TYPE;
};
template <typename T>
void test(const T& a)
{
// actually I would have used !is_foo<T>::value for the first arg
// but this check is fine to minimise the example
using MY_TYPE = typename std::conditional<
std::is_same<T, int>::value,
T,
typename T::M>::type; // <---Error: error: type 'int' cannot be used prior to '::' because it has no members
}
int main()
{
test(Foo<int>()); // MY_TYPE must be int
test(int()); // MY_TYPE must be int
return 0;
}
我認爲使用SFINAE和'void_t'對此有點矯枉過正。 – TartanLlama
@TartanLlama也許。然而,在學習TMP(我感覺OP在做)的時候,學習'void_t'並不會讓人感到痛苦。 – Rostislav