简体   繁体   English

如何在C ++中调用可变参数模板构造函数?

[英]How can I call variadic template constructor in c++?

I am learning c++ template technique. 我正在学习c ++模板技术。

I made a constructor with variadic template augments like following. 我用以下可变参数模板增强构造了一个构造器。

The class is simplified very much, so it does not have meaning. 该类非常简化,因此没有意义。 However I could not call the function. 但是我无法调用该函数。 Compiler tells me that it cannot call constructor directly. 编译器告诉我它不能直接调用构造函数。

How can I call it? 我怎么称呼它?

#include <utility>

class TemplateVariadicAugments {
public:

    template <typename FutureInnterTemplateClass, typename... Args>
    TemplateVariadicAugments(Args&&... args) : value_(std::forward<Args>(args)...) {}

    virtual ~TemplateVariadicAugments() = default;

    int value_;
};

void test_variadic_template_augments(void) {

    TemplateVariadicAugments a = TemplateVariadicAugments::template TemplateVariadicAugments<int, int>(1);

}

In the form you wrote it, there is no way to call the constructor. 在您编写的形式中,无法调用构造函数。 First, in C++ you cannot call a constructor by it's name, even in trivial cases: 首先,在C ++中,即使在平凡的情况下,也无法按其名称调用构造函数:

class A
{
public:
    A() {}
};

void foo()
{
    A::A(); // Illegal.
}

Then, as you can't call the constructor directly, you can't instantiate the template explicitly, so all template arguments must be deduced. 然后,由于您无法直接调用构造函数,因此无法显式实例化模板,因此必须推导出所有模板参数。 But in your case FutureInnterTemplateClass cannot be deduced, as it's not used anywhere in the constructor. 但是在您的情况下,无法推导出FutureInnterTemplateClass ,因为在构造函数中的任何地方都没有使用它。

The solution is to remove redundant argument from the constructor: 解决方案是从构造函数中删除冗余参数:

template <typename... Args>
TemplateVariadicAugments(Args&&... args) : value_(std::forward<Args>(args)...) {}

Now an object may be constructed as follows: 现在可以按以下方式构造对象:

TemplateVariadicAugments obj(1);

and Args in this case wil lbe correctly deduced to int . 在这种情况下, ArgsArgs可以正确推导为int

But in this case it's unclear what did you want to say with variadic template argument, as if you construct an object like this: 但是在这种情况下,您不清楚要使用可变参数模板参数说什么,就像构造一个这样的对象一样:

TemplateVariadicAugments obj(1, 2);

your value_ member initialization will become equivalent ti this code: 您的value_成员初始化将与此代码等效:

int value_(1, 2);

which is obviously ill-formed. 这显然是不正确的。

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

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