【发布时间】:2018-11-26 23:12:41
【问题描述】:
我试图看看我是否可以创建一个在其生命周期中只能包含几种类型之一的异构类型(两种模式),我想这样做:
//strong typed (heterogeneous) container
template<typename list>
struct STC
{
template<typename a>
STC(const a& value) :hc_(value), index_(TMP::elem_index<a, list>::value) {}
template<typename a>
STC(a&& value) : hc_(value), index_(TMP::elem_index<a, list>::value) {}
//imaginary compile time const
constexpr size_t index()const { return index_; }
typename TMP::index<list,index()>::type get() { return c_.get<index()>(); }
operator typename TMP::index<list,index()>::type ()const { return get(); }
private:
union_magic<list> c_;
const size_t index_;
};
其中 typename list 是模板元类型列表,TMP::elem_index 是用于检索列表元素索引的模板元函数,TMP::index 是用于检索具有已知索引的元素的元函数。
在我看来,没有办法跨越类数据成员和编译时间常数之间的界限。我错过了什么吗?这是错误的方法吗?或者这只是c++中不可能做到的事情,必须在运行时解决?
至于容器如何使用:
void call_with(char c)
{
std::cout << "calling function with char type: " << c << std::endl;
}
void call_with(int i)
{
std::cout << "calling function with int type: " << i<< std::endl;
}
int main()
{
STC<Cons<int, Cons<char, Nil>>> value(1);
call_with(value);
}
应该显示“调用 int 类型的函数:1”。
【问题讨论】:
-
你能举一个这个类模板的编译时应用的例子吗?即,它将以何种方式使用以使其需要编译时间?
-
list是a类型元素的列表,否则编译时错误? IE。你能把list描述成std::vector<a>吗? -
你能显示一个代码sn-p吗?这确实有助于使问题更清晰。
-
我想看看你将如何使用你想存储在
STC中的编译时间常数。 -
你的例子是不可能的。
STC<Cons<int, Cons<char, Nil>>>类型的所有对象都将导致调用相同的重载。重载解析只考虑类型。
标签: c++ templates template-meta-programming compile-time compile-time-constant