c++ - 在类模板中指定构造函数模板的整数模板参数

标签 c++ templates c++11 constructor

我正在创建一个 std::tuple 等同于 union(而不是 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 在类模板上匹配,而不是在构造函数模板上匹配。这是可以修复的吗?请注意, 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 的模板参数。

关于c++ - 在类模板中指定构造函数模板的整数模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28850608/

相关文章:

c++ - 在 C++ 中声明、操作和访问未对齐的内存

c++ - 如何重载模板函数以用于枚举?

python - 如何解决错误: missing binary operator before token "(" on mac?

c++ - 更改模板返回类型似乎对重载决议有影响

c++ - << , >> 运算符在循环中的作用是什么

c++ - C++中字符串和char数组声明的时间复杂度有什么区别?

c++ - 返回类型协变

Java 接口(interface)和模板的混淆

c++:有界数字的异构模板

c++ - 应该使用什么优雅的方法回调设计?