Pet*_*ome 2 c++ type-traits template-meta-programming c++11
在我的例子中,我有一个班级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;
}
Run Code Online (Sandbox Code Playgroud)
那么你可以UnFoo帮助你找到合适的类型:
template <typename T>
struct UnFoo {
using type = T;
};
template <typename T>
struct UnFoo<Foo<T>> {
using type = T;
};
template <typename T>
void test(const T& a)
{
using MY_TYPE = typename UnFoo<T>::type; //maybe with a helper to get rid of typename
}
Run Code Online (Sandbox Code Playgroud)
另一种选择是为其编写一个重载Foo<T>并将其委托给另一个函数,但这取决于你的实际test函数的作用.
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |