如何使用C++
我浏览了类似的线程,但是没有人回答我的问题。我正在寻找一种方法,以确保与两个竞争构造函数正确分辨率的过载,其中一个采用两个参数,另一个是一个变异模板构造函数。以此最小的代码示例:
template<typename Type>
class MyContainer<Type>
{
public:
using value_type = Type;
using size_type = std::size_t;
using const_reference = const value_type&;
MyContainer(size_type s = 0)
: containerSize(s)
{}
MyContainer(size_type s, const_reference v)
: A(s)
{
// Assign "s" identical values "v" in the container
}
template<typename... Args>
MyContainer(value_type&& v, Args&&... args)
:A()
{
// Assign each argument as an element of the container
}
private:
size_type containerSize;
}
我面临的问题是在不明确说明第一个参数的类型的情况下调用类构造函数,它总是称为variadic模板构造函数。以下是代码执行期间发生的事情:
// This calls the variadic template constructor (how to avoid it?)
MyContainer<int> container(10, 55);
// This calls the variadic template constructor (correct, desired)
MyContainer<int> container(1, 2, 3, 4, 5);
// This calls the "count-copies of value" constructor
MyContainer<int>::size_type containerSize = 10;
MyContainer<int> container(containerSize, 55);
是否有一种方法可以在调用构造函数并确保它不会调用variadic模板一个之前减少声明 containersize 的开销?
I have browsed similar threads, but none have answered my question. I am looking for a way to ensure correct overload resolution with two competing constructors, where one takes two parameters and the other one is a variadic template constructor. Take this minimal code example:
template<typename Type>
class MyContainer<Type>
{
public:
using value_type = Type;
using size_type = std::size_t;
using const_reference = const value_type&;
MyContainer(size_type s = 0)
: containerSize(s)
{}
MyContainer(size_type s, const_reference v)
: A(s)
{
// Assign "s" identical values "v" in the container
}
template<typename... Args>
MyContainer(value_type&& v, Args&&... args)
:A()
{
// Assign each argument as an element of the container
}
private:
size_type containerSize;
}
The problem I am facing is that calling the class constructor without explicitly stating the first parameter's type beforehand, it always calls the variadic template constructor. Here is what happens during code execution:
// This calls the variadic template constructor (how to avoid it?)
MyContainer<int> container(10, 55);
// This calls the variadic template constructor (correct, desired)
MyContainer<int> container(1, 2, 3, 4, 5);
// This calls the "count-copies of value" constructor
MyContainer<int>::size_type containerSize = 10;
MyContainer<int> container(containerSize, 55);
Is there a way to reduce the overhead of declaring containerSize before calling the constructor and making sure it does not invoke the variadic template one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论