【发布时间】:2014-02-26 11:50:36
【问题描述】:
考虑一个模板类:
template <class First, class Second, class Third, class Fourth>
class MyClass;
为某些模板参数集添加成员函数的正确方法是什么?
例如,当Second是std::string()时,如何添加成员f()?
这是我找到的并且我传统上使用的方法:
#include <iostream>
#include <type_traits>
#include <array>
template <class Container>
struct Array
{
Container data;
template <class... Dummy,
class = typename std::enable_if<sizeof...(Dummy) == 0>::type,
class = typename std::enable_if<
std::tuple_size<
typename std::conditional<sizeof...(Dummy),
Container,
Container
>::type
>::value == 1
>::type
>
inline typename Container::value_type& value(Dummy...)
{return data[0];}
};
int main()
{
Array<std::array<double, 0>> array0; // Does not have the value() member
Array<std::array<double, 1>> array1; // Have the value() member
Array<std::array<double, 2>> array2; // Does not have the value() member
Array<std::array<double, 3>> array3; // Does not have the value() member
}
它运作良好,但它更像是一种元编程技巧,而不是一种干净/标准的方式。
【问题讨论】:
-
如果您将 C++1y 列为一个选项,那么这就是 easy。 :)
标签: c++ templates c++11 metaprogramming template-specialization