首页 > 解决方案 > C++:递归匹配参数类型与类模板类型

问题描述

我希望实现这样的类型匹配功能:

    MyClass<int, bool> temp;
    temp.print(-1, false);           // works
    temp.print(-1);                  // compile error, too less argument
    temp.print(-1, "string");        // compile error, wrong type
    temp.print(-1, false, 'c');      // compile error, too many arguments

基本上,当给定模板参数时,MyClass的函数print接受完全相同类型的参数,不多也不少。

这是我目前的实现:

template<class... ClassType>
class MyClass {
public:
    template<typename... ArgType>
    void print(ArgType... args) {
        matchType<ClassType...>(args...);
    }

private:
    template<typename Type>
    void matchType(Type t) {
        std::cout << "matching " << t << "\n";
        std::cout << "end\n";
    }

    template<typename FirstType, typename... Rest>
    void matchType(FirstType firstArg, Rest... args) {
        std::cout << "matching " << firstArg << "\n";
        matchType<Rest...>(args...);
    }
};

但它无法检测和匹配它为代码编译得很好的类型:

    MyClass<int, bool> temp;
    temp.print(-1, false);           // works
    temp.print(-1, "string");        // works, shouldn't work
    temp.print(-1, false, 'c');      // works, shouldn't work

有人可以向我解释我做错了什么吗?

实时代码

标签: c++templates

解决方案


#include <iostream>

template<class... ClassType>
class MyClass {
public:
    template<typename... ArgType>
    void print(ArgType... args) = delete;

    void print(ClassType ... args) {
        std::cout << "works\n";
    }
};

int main()
{
    MyClass<int, bool> temp;
    temp.print(-1, false);            // ok

    temp.print(-1);                   // error
    temp.print(-1, "string");         // error
    temp.print(-1, false, 'c');       // error
    temp.print(-1L, false);           // error
}

推荐阅读