c++ - c++模板中的多个类型名参数? (可变参数模板)

标签 c++ templates variadic-templates template-specialization

如何在 c++ 模板中拥有多个类型名参数?

#ifndef _CALL_TEMP_H
#define _CALL_TEMP_H

#include <string>
#include <iostream>

template <typename Sig>
class Foo;

template <typename A, typename B>
class Foo
{
    public:
        void output() {
            std::cout << a_ << b_ << std::endl;
        }
        A a_;
        B b_;
};

template <typename A, typename B, typename C>
class Foo
{
    public:
        void output() {
            std::cout << a_ << b_ << c_ << std::endl;
        }
        A a_;
        B b_;
        C c_;
};

#endif

用法:

int main()
{
    Foo<int ,int> doubleint;
    doubleint.a_ = 1;
    doubleint.b_ = 2;
    doubleint.output();
//  Foo<int , int , std::string> comp;
//  comp.a_ = 1;
//  comp.b_ = 2;
//  comp.c_ = "haha";
//  comp.output();
    return 0;
}

但它不会编译。我怎样才能让它编译?

最佳答案

只需使用可变参数模板声明一个主模板,然后专门针对每个支持的模板参数数量。例如:

#ifndef CALL_TEMP_H
#define CALL_TEMP_H

#include <iostream>

template <typename...> class Foo;

template <typename A, typename B>
class Foo<A, B>
{
public:
    void output() {
        std::cout << a_ << b_ << '\n';
    }
    A a_;
    B b_;
};

template <typename A, typename B, typename C>
class Foo<A, B, C>
{
public:
    void output() {
        std::cout << a_ << b_ << c_ << '\n';
    }
    A a_;
    B b_;
    C c_;
};

#endif

您不能使用 C++11,并且您想保留类似的符号,您需要使用模板默认参数模拟可变参数列表。这将隐式限制 templare 参数的数量,但由于无论如何您都在专门化模板,所以这个限制并不重要。

如果可以接受使用不同的符号,您也可以使用类似于函数声明的东西来实例化和专门化您的模板:

template <typename> class Foo;

template <typename A, typename B>
class Foo<void(A, B)> {
    ...
};
template <typename A, typename B, typename C>
class Foo<void(A, B, C)> {
    ...
};
...
Foo<void(int, int)>                   f2;
Foo<void(int, int, std::string)> f3;

符号的变化是否可以接受取决于您对类模板的使用。但是,如果没有 C++11,您将无法获得理想的解决方案。

顺便说一句,don't overuse std::endl : 使用 '\n' 表示行尾。如果您真的要刷新流,请使用 std::flush。此外,_CALL_TEMP_H 是标准 C++ 库保留的名称,所有以下划线后跟大写字符的名称也是如此:不要在您自己的代码中使用这些名称,除非有是使用它们的明确许可(例如,__FILE____LINE__ 被保留,但被授予使用它们的明确许可)。

关于c++ - c++模板中的多个类型名参数? (可变参数模板),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19923353/

相关文章:

c++ - 模板成员函数和非模板重载的参数推导

c++ - std::pair 替换因 std::size_t 失败

c++ - boost::range::join 一个自定义调用中的多个范围

c++ - 可变参数模板中更好的包扩展语法?

c++ - 将按引用传递和按值传递混合到可变参数模板函数是否有效?

c++ - boost::filesystem::unicode 文件路径的路径?

c++ - 如何使用 Windows 内存 dc (c++) 创建 OpenGL 上下文

c++ - 如何定义一个lambda函数来捕获类的 'this'指针?

java - 使用 undefined symbol 加载 JNI 时崩溃

c++ - 以成员函数指针为参数的可变参数模板