简体   繁体   English

在类模板中指定构造函数模板的积分模板参数

[英]Specify integral template argument of constructor template inside a class template

I am creating a std::tuple equivalent for a union (instead of a struct ). 我正在为union创建一个std::tuple等效项(而不是struct )。 To do so, I also added a constructor template, where the first template argument is size_t idx , to initize the idx th element of the union . 要做到这一点,我还添加了一个构造函数模板,其中第一个模板参数是size_t idx ,以initize的IDX 的元素union Moreover, there is another variadic template to specify what the argments of the actual type constructor are. 此外,还有另一个variadic template用于指定实际类型构造函数的参数是什么。

Unfortunately, I can't seem to specify the idx template argument when calling the constructor, and it is also not implied (as it is not part of the argument list). 不幸的是,在调用构造函数时,我似乎无法指定idx模板参数,而且也没有暗示(因为它不属于参数列表)。 Is there any way around this? 有没有办法解决? How can I specify a size_t contructor template argument? 如何指定size_t构造器模板参数?

Example code: 示例代码:

#include <iostream>

template<typename T>
struct Foo
{
    T d_val;
    size_t d_other_val;
    template<size_t idx>
    Foo(T val)
    {
        d_val = val;
        d_other_val = idx;
    }
};


int main() {
    Foo<double> f = Foo<4>(2.6);

    std::cout << f.d_val << " " << f.d_other_val << '\n';
}

Source: http://ideone.com/UeBvF5 来源: http//ideone.com/UeBvF5

Of course, the 4 is matched on the class template, and not the constructor template. 当然,4是在类模板上匹配的,而不是在构造函数模板上匹配的。 Is this fixable? 这个可以解决吗? Note that idx should be a compile time thing, and not a normal constructor argument. 请注意,idx应该是编译时的东西,而不是常规的构造函数参数。 Although in this example, that would be the trivial solution. 尽管在此示例中,这将是微不足道的解决方案。

PS: the problem of course is, that in general constructor templates are implied by the arguments with which the constructor is called. PS:当然,问题在于,通常,构造函数模板由调用构造函数的参数隐含。 Implicit specification is to the best of my knowledge not possible for the idx template argument. 据我所知,隐式规范对于idx模板参数是不可能的。

[temp.arg.explicit]/7 reads: [temp.arg.explicit]/7读取:

[ Note: Because the explicit template argument list follows the function template name, and because conversion member function templates and constructor member function templates are called without using a function name, there is no way to provide an explicit template argument list for these function templates. [ 注意:因为显式模板参数列表紧随功能模板名称,并且由于在不使用函数名称的情况下调用转换成员函数模板和构造函数成员函数模板,所以无法为这些功能模板提供显式模板参数列表。 —end note ] —尾注 ]

So you have to either pass size_t idx as a regular parameter, or add it as struct Foo 's template parameter. 因此,您必须将size_t idx作为常规参数传递,或将其添加为struct Foo的模板参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM