在 class 模板中指定构造函数模板的整数模板参数

Specify integral template argument of constructor template inside a class template

我正在为 union 创建一个 std::tuple 等价物(而不是 struct)。为此,我还添加了一个构造函数模板,其中第一个模板参数是 size_t idx,以初始化 union 的 idxth 元素。此外,还有另一个 variadic template 来指定实际类型构造函数的参数是什么。

不幸的是,我似乎无法在调用构造函数时指定 idx 模板参数,而且它也不是隐含的(因为它不是参数列表的一部分)。有没有办法解决?如何指定 size_t 构造函数模板参数?

示例代码:

#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';
}

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

当然,4 在 class 模板上匹配,而不是构造函数模板。这是可以修复的吗?请注意, idx 应该是编译时的东西,而不是普通的构造函数参数。虽然在这个例子中,这将是微不足道的解决方案。

PS:问题当然是,通常构造函数模板是由调用构造函数的参数隐含的。据我所知,隐式规范对于 idx 模板参数是不可能的。

[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 ]

因此您必须将 size_t idx 作为常规参数传递,或者将其添加为 struct Foo 的模板参数。