【发布时间】:2020-09-16 02:33:21
【问题描述】:
出于测试目的,我想用简单的std::initializer_list 调用构造函数。假设值无关紧要,长度、值和类型在编译时是已知的,例如{ 42, 42, 42,... N-times }。
由于它的构造函数是私有的,我尝试了一些包扩展:
template< int Count, typename ValueType, int Value, int... Values >
struct Generator
: Generator< Count-1, ValueType, Value, Value, Values... >
{};
template< typename ValueType, int Value, int... Values >
struct Generator< 0, ValueType, Value, Values... >
{
static constexpr inline std::initializer_list<ValueType>
get()
{ return { static_cast<ValueType>(Values)... }; }
};
所以Generator<3,int,10>::get() 给了我{10,10,10},是的!但我似乎有一个终身问题,因为initializer_list 只是一个代理对象,从函数内的{..}-表达式返回。测试没有看到我期望的值。我是否忽略了什么?
struct A {
A(std::initializer_list<int> l)
{ for(auto i:l) std::cout << i << std::endl; }
};
int main() {
A a { Generator<3, int, 10>::get() };
return 0;
}
// prints:
// 32765
// 1762362376
// 32765
【问题讨论】:
标签: c++ c++11 constructor initializer-list